3

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!

4
  • 1
    FYI: $url[fragment] means "get the value of the constant fragment and use this to get the key from $url". You probably means $url['fragment']? Fragments are stuff after # btw. If you're looking for the variables between ? and # this is the "query".
    – h2ooooooo
    Commented Dec 23, 2013 at 20:21
  • Are you simply looking for $_GET['x'] or are you parsing a URL separate from the one belonging to your script?
    – McAden
    Commented Dec 23, 2013 at 20:27
  • Ok, so after the ? in the url is called the argument. Got that now. I already understood $_GET[] but my thought is about processing the $url and not using that function.
    – Maelish
    Commented Dec 23, 2013 at 20:38
  • query or Query? Commented Oct 5, 2021 at 18:38

5 Answers 5

10

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.

3

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.

1

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.

0

As a one-liner with no error checking

parse_str(parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY), $query);

$query will contain the query string parameters.
Unlike PHP's $_GET, this will work with query parameters of any length.

0

I highly recommend using this URL wrapper (which I have written).

It is capable of parsing URLs of complexity like protocol://username:[email protected]:80/some/path?query=value#fragment and has many more goodies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.