Parsing URL query in PHP

Assuming a URL of www.domain.org?x=1&y=2&z=3, what would be a smart method to separate out the query elements of a URL in PHP without using GET or REQUEST?

  $url = parse_url($url);
  echo $url[fragment];

I don't think it's possible to return query parts separately, is it? From what I can tell, the query will just say x=1&y=2&z=3, but please let me know if I am wrong. Otherwise, what would you do to parse the $url[query]?


Fragment should be Query instead. Sorry for the confusion; I am learning!


Solution 1:

You can take the second step and parse the query string using parse_str.

$url = 'www.domain.org?x=1&y=2&z=3';
$url_parts = parse_url($url);
parse_str($url_parts['query'], $query_parts);
var_dump($query_parts);

I assumed you meant the query string instead of the fragment because there isn't a standard pattern for fragments.

Solution 2:

The parse_url function returns several components, including query. To parse it you should run parse_str.

$parsedUrl = parse_url($url);
parse_str($parsedUrl['query'], $parsedQueryString);

If you are going just to parse your HTTP request URL:

  • use the $_REQUEST['x'], $_REQUEST['y'], and $_REQUEST['z'] variables to access the x, y, and z parameters;

  • use $_SERVER['QUERY_STRING'] to get the whole URL query string.

Solution 3:

I was getting errors with some of the answers, but they did lead me to the right answer.

 $url = 'www.domain.org?x=1&y=2&z=3';
 $query = $url[query]; 
 parse_str($query);
 echo "$x &y $z";

And this outputs 1 2 3, which is what I was trying to figure out.