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]
?
Edit: Fragment should be Query instead. Sorry for the confusion, I am learning!
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.
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 $_REQUEST['x']
, $_REQUEST['y']
, $_REQUEST['z']
variables to access x,y,z parameters;
use $_SERVER['QUERY_STRING']
to get whole URL querystring.
I was getting errors with some of the answers above but they did lead me to the right answer. Thanks guys.
$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.
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 params of any length
I highly recommend using this url wrapper https://github.com/weew/url (which I have written)
It is capable of parsing urls of complexity like protocol://username:password@subdomain.domain.tld:80/some/path?query=value#fragment
and has many more goodies .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.