Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method="GET" gives empty $_GET, method="POST" gives non empty $_GET. Why? (PHP 5.6.6)

test.php:

<?php
var_dump($_GET);
var_dump($_POST);

submit_get.php:

<form action="test.php?param=some" method="GET">
  <input type="submit" value="Submit">
</form>

submit_post.php:

<form action="test.php?param=some" method="POST">
  <input type="submit" value="Submit">
</form>

Submitting submit_get.php gives something like this:

array (size=0)
empty
array (size=0)
empty

Submitting submit_post.php outputs something like this:

array (size=1)
'param' => string 'some' (length=4)
array (size=0)
empty

So, I do not quite get how are POST and GET methods are connected with $_POST and $_GET PHP variables and why a submitted form with method="POST" outputs empty $_POST and non-empty $_GET?

like image 959
olegzhermal Avatar asked Sep 15 '25 23:09

olegzhermal


1 Answers

A form sent via GET needs to have all values defined inside the form. The browser will then create the query string from these values (according to form evaluation rules, things like "successful controls" etc). Creating this query string means that any existing query string in the action URL gets replaced. If you need to have a fixed value inside the query string, use hidden form fields.

When using POST forms, all data from the form goes into the body of the request instead of replacing the query string. So there is no replacement taking place, and the query string in the action URL survives.

You probably are taking the superglobal variable names POST and GET too literal. $_GET is the parsed query string, it's independent of the HTTP method, i.e. it will always be present, even with POST, PUT and DELETE requests. $_POST is the parsed HTTP body when conforming to some constraints (the content-type header has to specify either application/x-www-form-urlencoded or multipart/form-data, and I think the method really has to be "POST" - "PUT" won't work that way, and "DELETE" must not have a HTTP body). Note that when NOT conforming to the constraints, even if you'd use the POST method, you won't get any data inside $_POST.

like image 96
Sven Avatar answered Sep 18 '25 13:09

Sven