How to set $_GET variable

2019-01-15 13:02发布

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

9条回答
走好不送
2楼-- · 2019-01-15 13:07

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.

查看更多
神经病院院长
3楼-- · 2019-01-15 13:07

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'];
查看更多
欢心
4楼-- · 2019-01-15 13:12

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)
)
查看更多
等我变得足够好
5楼-- · 2019-01-15 13:16

$_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.

查看更多
ら.Afraid
6楼-- · 2019-01-15 13:22

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');
查看更多
Viruses.
7楼-- · 2019-01-15 13:23

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.

查看更多
登录 后发表回答