Search code examples
phparraysquery-stringname-value

How can I convert a query string to variables in PHP?


I have a string like this stored in mysql table:

?name1=value1&name2=value2&name3=value3

originally this data was only going to be used to send GET data to another script but now i find myself needing it for other things.

is there a predefined function in PHP for turning these pairs into variable or an array? or will I have to do it manually?


Solution

  • The (poorly-named) PHP function parse_str can do this, though you will need to first trim off the initial question mark.

    $arr = array();
    parse_str($str, $arr);
    print_r($arr);
    

    There are some caveats to this function alluded to in the manual page:

    • If you call it without the second array parameter it will write the values into the current scope as local variables. This can be dangerous if the string contains keys that may change the value of variables already present in your program.
    • The magic_quotes_gpc setting affects how this function operates, since this is the routine used internally by PHP to decode query strings and urlencoded POST bodies.

    If you need a portable solution that is not affected by the magic_quotes_gpc setting then it's reasonably straightforward to write a decoding function manually, using urldecode to handle the value encoding:

    function parseQueryString($queryString) {
        $result = array();
        $pairs = explode("&", $queryString);
        foreach ($pairs as $pair) {
            $pairArr = split("=", $pair, 2);
            $result[urldecode($pairArr[0])] = urldecode($pairArr[1]);
        }
        return $result;
    }
    

    This solution will probably be slightly slower than the built-in parse_args function, but has the benefit of consistent behavior regardless of how PHP is configured. Of course you will again need to first strip off the ? from the beginning, which is not included in either example.