Get URL query string parameters

前端 未结 11 1323
长情又很酷
长情又很酷 2020-11-22 17:41

What is the \"less code needed\" way to get parameters from a URL query string which is formatted like the following?

www.mysite.com/category/subcateg

相关标签:
11条回答
  • 2020-11-22 17:44

    The function parse_str() automatically reads all query parameters into an array.

    For example, if the URL is http://www.example.com/page.php?x=100&y=200, the code

    $queries = array();
    parse_str($_SERVER['QUERY_STRING'], $queries);
    

    will store parameters into the $queries array ($queries['x']=100, $queries['y']=200).

    Look at documentation of parse_str


    EDIT

    According to the PHP documentation, parse_str() should only be used with a second parameter. Using parse_str($_SERVER['QUERY_STRING']) on this URL will create variables $x and $y, which makes the code vulnerable to attacks such as http://www.example.com/page.php?authenticated=1.

    0 讨论(0)
  • 2020-11-22 17:44

    Thanks to @K. Shahzad This helps when you want the rewrited query string without any rewrite additions. Let say you rewrite the /test/?x=y to index.php?q=test&x=y and you want only want the query string.

    function get_query_string(){
    
        $arr = explode("?",$_SERVER['REQUEST_URI']);
        if (count($arr) == 2){
            return "";
        }else{
            return "?".end($arr)."<br>";
        }       
    }
    $query_string = get_query_string();
    
    0 讨论(0)
  • 2020-11-22 17:47

    If you want the whole query string:

    $_SERVER["QUERY_STRING"]
    
    0 讨论(0)
  • 2020-11-22 17:47

    For getting each node in the URI, you can use function explode() to $_SERVER['REQUEST_URI']. If you want to get strings without knowing if it is passed or not. you may use the function I defined myself to get query parameters from $_REQUEST (as it works both for POST and GET params).

    function getv($key, $default = '', $data_type = '')
    {
        $param = (isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default);
    
        if (!is_array($param) && $data_type == 'int') {
            $param = intval($param);
        }
    
        return $param;
    }
    

    There might be some cases when we want to get query parameters converted into Integer type, so I added the third parameter to this function.

    0 讨论(0)
  • 2020-11-22 17:48

    I will recommended best answer as

    <?php echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!'; ?>

    Assuming the user entered http://example.com/?name=Hannes

    The above example will output:

    Hello Hannes!

    0 讨论(0)
  • 2020-11-22 17:49

    $_SERVER['QUERY_STRING'] contains the data that you are looking for.


    DOCUMENTATION

    • php.net: $_SERVER - Manual
    0 讨论(0)
提交回复
热议问题