How to set $_GET variable

前端 未结 9 460
梦如初夏
梦如初夏 2020-12-03 21:22

How do i set the variable that the $_GET function will be able to use, w/o submitting a form with action = GET?

9条回答
  •  情深已故
    2020-12-03 21:40

    One way to set the $_GET variable is to parse the URL using parse_url() and then parse the $query string using parse_str(), which sets the variables into the $_GET global.

    This approach is useful,

    • if you want to test GET parameter handling without making actual queries, e.g. for testing the incoming parameters for existence and input filtering and sanitizing of incoming vars.
    • and when you don't want to construct the array manually each time, but use the normal URL

    function setGetRequest($url)
    {
        $query = parse_url($url, PHP_URL_QUERY);
        parse_str($query, $_GET);
    }
    
    $url = 'http://www.example.com/test.php?a=10&b=plop';
    
    setGetRequest($url);   
    
    var_dump($_GET);
    

    Result: $_GET contains

    array (
      'a' => string '10' (length=2)
      'b' => string 'plop' (length=4)
    )
    

提交回复
热议问题