How to get and disect the query string appended into a url? PHP

后端 未结 6 1702
不知归路
不知归路 2021-01-22 04:53

I am trying to develop a PHP class which would enable me to get the query string appended into a url and process it according to the variables passed. How can this be done?

6条回答
  •  [愿得一人]
    2021-01-22 05:34

    If you want access to the URL parameters as a string you can use this:

    $_SERVER['QUERY_STRING']
    

    But, I'm not sure how that would be any more useful than $_GET. You said:

    I wont be sure of the variable names

    You can iterate through the $_GET array with a foreach loop:

    foreach ($_GET as $key => $val) {
        echo $key . ": " . $val;
    }
    

    However... if you're talking about an arbitrary URL (not necessarily the one which was requested), then the above methods won't work since they obviously won't be in $_GET. Instead you can use parse_url

    $url = 'http://username:password@hostname/path?arg=value#anchor';
    
    print_r(parse_url($url));
    
    echo parse_url($url, PHP_URL_QUERY);
    

    Output:

    Array
    (
        [scheme] => http
        [host] => hostname
        [user] => username
        [pass] => password
        [path] => /path
        [query] => arg=value
        [fragment] => anchor
    )
    arg=value
    

提交回复
热议问题