Accessing a $_GET variable whose value contains '&'
What is a good workaround for fields that have '&'? I have a site that is getting stuff via $_GET, but some of the fields are, for example: 'Pants & shorts'... When I put this in a URL it gets all messed up :) Any PHP fix for it? :)
F开发者_如何学Goor example:
http://localhost/clothes/?sex=both&order=newest&time=all&type=Pants%20&%20Shorts
Thank you!
Check the PHP manual for urlencode()
http://nl.php.net/manual/en/function.urlencode.php
http://www.php.net/manual/en/function.urlencode.php
or:
http://www.php.net/manual/en/function.http-build-query.php
when writing the url:
http://localhost/clothes/<? echo urlencode('pants & shorts'); ?>/
PHP seems to de-encode names when they are url-encoded, so you could use:
[pants & shorts] == [pants%20%26%20shorts]
When building URI query, either use http_build_query
or rawurlencode
:
$query = array('sex'=>'both', 'order'=>'newest', 'time'=>'all', 'type'=>'Pants & Shorts');
$url = 'http://localhost/clothes/?'.http_build_query($query);
$url = 'http://localhost/clothes/?sex=both&order=newest&time=all&type='.rawurlencode('Pants & Shorts');
One workaround I have used (even though it might not be the best solution) is to change the & with text and after you retrieve it via $_GET you can change it back.
For example you would change the & for "andsign" before sending it:
$your_var_without_and = str_replace("&", "andsign", $your_var);
And change it back after retrieving it:
$your_var_without_and = $_GET['your_var_without_and'];
$your_var = str_replace("andsign", "&", $your_var_without_and);
精彩评论