note 76792 added to function.parse-str
| From: | EvanK at osu1 dot php dot net | Date: | Tue, 31 Jul 2007 02:43:56 +0000 |
| Subject: | note 76792 added to function.parse-str | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-129063@lists.php.net to get a copy of this message | ||
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard
way, when it comes to duplicate fields. If multiple fields of the same name exist in a query
string, every other web processing language would read them into an array, but PHP silently
overwrites them:
<?php
# silently fails to handle multiple values
parse_str('foo=1&foo=2&foo=3');
# the above produces:
$foo = array('foo' => '3');
?>
Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve
the same effect.
<?php
# bizarre php-specific behavior
parse_str('foo[]=1&foo[]=2&foo[]=3');
# the above produces:
$foo = array('foo' => array('1', '2', '3') );
?>
This can be confusing for anyone who's used to the CGI standard, so keep it in mind. As an
alternative, I use a "proper" querystring parser function:
<?php
function proper_parse_str($str) {
# result array
$arr = array();
# split on outer delimiter
$pairs = explode('&', $str);
# loop through each pair
foreach ($pairs as $i) {
# split into name and value
list($name,$value) = explode('=', $i, 2);
# if name already exists
if( isset($arr[$name]) ) {
# stick multiple values into an array
if( is_array($arr[$name]) ) {
$arr[$name][] = $value;
}
else {
$arr[$name] = array($arr[$name], $value);
}
}
# otherwise, simply stick it in a scalar
else {
$arr[$name] = $value;
}
}
# return result array
return $arr;
}
$query = proper_parse_str($_SERVER['QUERY_STRING']);
?>
----
Server IP: 69.147.83.197
Probable Submitter: 98.199.250.194
----
Manual Page -- http://www.php.net/manual/en/function.parse-str.php
Edit -- https://master.php.net/note/edit/76792
Del: integrated -- https://master.php.net/note/delete/76792/integrated
Del: useless -- https://master.php.net/note/delete/76792/useless
Del: bad code -- https://master.php.net/note/delete/76792/bad+code
Del: spam -- https://master.php.net/note/delete/76792/spam
Del: non-english -- https://master.php.net/note/delete/76792/non-english
Del: in docs -- https://master.php.net/note/delete/76792/in+docs
Del: other reasons-- https://master.php.net/note/delete/76792
Reject -- https://master.php.net/note/reject/76792
Search -- https://master.php.net/manage/user-notes.php