How to set $_GET variable

前端 未结 9 457
梦如初夏
梦如初夏 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:32

    For the form, use:

    <form name="form1" action="<?=$_SERVER['PHP_SELF'];?>" method="get">
    

    and for getting the value, use the get method as follows:

    $value = $_GET['name_to_send_using_get'];
    
    0 讨论(0)
  • 2020-12-03 21:37

    $_GET contains the keys / values that are passed to your script in the URL.

    If you have the following URL :

    http://www.example.com/test.php?a=10&b=plop
    

    Then $_GET will contain :

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


    Of course, as $_GET is not read-only, you could also set some values from your PHP code, if needed :

    $_GET['my_value'] = 'test';
    

    But this doesn't seem like good practice, as $_GET is supposed to contain data from the URL requested by the client.

    0 讨论(0)
  • 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)
    )
    
    0 讨论(0)
  • 2020-12-03 21:49

    If you want to fake a $_GET (or a $_POST) when including a file, you can use it like you would use any other var, like that:

    $_GET['key'] = 'any get value you want';
    include('your_other_file.php');
    
    0 讨论(0)
  • 2020-12-03 21:50

    You could use the following code to redirect your client to a script with the _GET variables attached.

    header("Location: examplepage.php?var1=value&var2=value");
    die();
    

    This will cause the script to redirect, make sure the die(); is kept in there, or they may not redirect.

    0 讨论(0)
  • 2020-12-03 21:51

    The $_GET variable is populated from the parameters set in the URL. From the URL http://example.com/test.php?foo=bar&baz=buzz you can get $_GET['foo'] and $_GET['baz']. So to set these variables, you only have to make a link to that URL.

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