PHP $_REQUEST $_GET or $_POST

2019-03-27 20:21发布

问题:

Say I have a form:

<form action="form.php?redirect=false" method="post">
    <input type="hidden" name="redirect" value="true" />
    <input type="submit" />
</form>

On form.php:

var_dump($_GET['redirect']) // false
var_dump($_POST['redirect']) // true
var_dump($_REQUEST['redirect']) // true

How do I get the injected query string parameter to override the $_POST value so $_REQUEST['redirect'] will = false ?

回答1:

If you want to change precedence of $_GET over $_POST in the $_REQUEST array, change the request_order directive in php.ini.

The default value is:

request_order = "GP"

P stands for POST and G stands for GET, and the later values have precedence, so in this configuration, a value in the query string will override a value passed by POST in the $_REQUEST array. If you want POST to override GET values, just switch them around like so:

request_order = "PG"

You'll need to restart the webserver/php for that to take effect.

(Edited to use the more appropriate request_order as Brad suggested, rather than variables_order)



回答2:

See the request_order directive in PHP.ini.

Really though, you should be explicitly using the superglobal that you specifically want. Otherwise, you cannot rely on consistent behavior from system to system, and then your variables can be accidentally overwritten.



回答3:

See the request order parameter of PHP. Here you can set whether the array fills post, get, cookie or any combo thereof.



回答4:

$_REQUEST['redirect'] = $_POST['redirect'];

or

$_REQUEST['redirect'] = $_GET['redirect'];

depending on what you want



回答5:

If you meant false at that last line there, and want $_REQUEST to still have data from both POST and GET data, and don't want to mess with the config, use this:

$_REQUEST = array_merge($_POST, $_GET);