Reputation: 11423
I noticed that I can use $_GET
inside a POST request, why is that possible?
HTML form:
<form method="POST" action="test.php?id=123">
<input type="text" name="foo">
<input type="submit">
</form>
test.php:
<?php
var_dump($_GET, $_POST);
Output:
array (size=1)
'id' => string '123' (length=3)
array (size=1)
'foo' => string 'bar' (length=3)
Upvotes: 0
Views: 93
Reputation: 11423
In contrary to what is suggested by their names, $_GET
and $_POST
are not tied to the GET and POST methods of the HTTP specification.
The query string (which is represented as an associative array in PHP's $_GET
variable) can be part of any URL, wether you are doing a GET, POST, PUT or any other method on that URL. Although query strings are most commonly used with GET methods, they are certainly not limited to them. So, when POSTing a form to a URL that contains a query string (as per the example), the keys and values of the query string will be available in the $_GET
variable.
$_QUERY_STRING
would probably have been a better name for this variable.
It works slightly different the other way around. Although the POST method is not the only one that can contain a body (for instance, a PUT request can as well), some testing reveals that $_POST
only contains data in case of a POST request - it is empty in all other cases.
PHP does not have a $_PUT
variable to use with PUT request, probably because browsers only support GET and POST requests for form submission. Instead, you can use file_get_contents("php://input")
to read from the incoming stream to PHP, and then use str_parse()
to load the keys and values as an associative array:
parse_str(file_get_contents("php://input"), $data);
Upvotes: 1