Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP parse_str of URL query returns array keys with 'amp' in key name

Environment: Wordpress (latest) on test site on Host (JustHost), with PHP version 5.4.43.

Using parse_str on a URL query, the resulting array returns array key names of amp;keyname . Example code:

$querystring = "ie=UTF8&qid=1468851514&sr=8-1&keywords=there&tag=sitename-20";
parse_str($querystring, $queryarray);
echo "<pre>";
print_r($queryarray);
echo "</pre>";

Returns

Array
(
    [ie] => UTF8
    [amp;qid] => 1468851514
    [amp;sr] => 8-1
    [amp;keywords] => there
    [amp;tag] => sitename-20
)

Why is the 'amp;' in the key name?

Is this a PHP version issue (it seems to work OK in a EasyPHP local environment - version 5.4.24, but not on my test WP server on my hosting place)? Or am I confused (again)?

like image 856
Rick Hellewell Avatar asked Jul 26 '16 19:07

Rick Hellewell


2 Answers

&'amp; must only be used when outputting URLs in HTML/XML data.

You can try use html_entity_decode()

$querystring = "ie=UTF8&qid=1468851514&sr=8-1&keywords=there&tag=sitename-20";
parse_str(html_entity_decode($querystring), $queryarray);
echo "<pre>";
print_r($queryarray);
echo "</pre>";

I hope it help.

like image 81
Hugo E Sachez Avatar answered Nov 15 '22 00:11

Hugo E Sachez


If you are sure that $querystring doesn't contain other encoded entities, you can use html_entity_decode, as @Hugo E Sachez suggests. But in some complex systems $querystring may come from a place that you don't have control of, and it may contain entities that were encoded on purpose as a safety measure, like &quot;, or &lt;, or &gt; etc...

So, if you decode all entities, and then parse data, and then somehow return this data to user, probably some unwanted <script> can be executed. I assume it would be safer to replace only &amp; with &, and keep other entities encoded. Like this: parse_str(str_replace('&amp;', '&', $querystring), $queryarray);

Correct me if I am wrong

like image 45
Blaine_ Avatar answered Nov 15 '22 00:11

Blaine_