PHP to check if a URL contains a query string

前端 未结 4 457
闹比i
闹比i 2020-12-05 20:11

This is an easy one. There seem to be plenty of solutions to determine if a URL contains a specific key or value, but strangely I can\'t find a solution for determining if U

相关标签:
4条回答
  • 2020-12-05 20:31

    Like this:

    if (isset($_SERVER['QUERY_STRING'])) {
    
    }
    
    0 讨论(0)
  • 2020-12-05 20:43

    The easiest way is probably to check to see if the $_GET[] contains anything at all. This can be done with the empty() function as follows:

    if(empty($_GET)) {
        //No variables are specified in the URL.
        //Do stuff accordingly
        echo "No variables specified in URL...";
    } else {
        //Variables are present. Do stuff:
        echo "Hey! Here are all the variables in the URL!\n";
        print_r($_GET);
    }
    
    0 讨论(0)
  • 2020-12-05 20:47

    For any URL as a string:

    if (parse_url($url, PHP_URL_QUERY))
    

    http://php.net/parse_url

    If it's for the URL of the current request, simply:

    if ($_GET)
    
    0 讨论(0)
  • 2020-12-05 20:47

    parse_url seems like the logical choice in most cases. However I can't think of a case where '?' in a URL would not denote the start of a query string so for a (very minor) performance increase you could go with

    return strpos($url, '?') !== false;

    Over 1,000,000 iterations the average time for strpos was about 1.6 seconds vs 1.8 for parse_url. That being said, unless your application is checking millions of URLs for query strings I'd go for parse_url.

    0 讨论(0)
提交回复
热议问题