$_SERVER['REQUEST_METHOD'] fetches the request method used to access the page. Request methods are 'GET', 'HEAD', 'POST', 'PUT'.
$_SERVER['REQUEST_METHOD'] is one of the PHP server variables. It determines: Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'. It's generally defaulted to GET though, so don't rely on it for determining if a form has been posted or not (eg if not POST then must be GET etc).
The method designates the type of request being made to the web server. The most common types of request methods are GET and POST but there are many others, including HEAD, PUT, DELETE, CONNECT, and OPTIONS. GET and POST are widely supported while support for other methods is sometimes limited but expanding.
Well, they don't do the same thing, really.
$_SERVER['REQUEST_METHOD']
contains the request method (surprise).
$_POST
contains any post data.
It's possible for a POST request to contain no POST data.
I check the request method — I actually never thought about testing the $_POST
array. I check the required post fields, though. So an empty post request would give the user a lot of error messages - which makes sense to me.
if ($_SERVER['REQUEST_METHOD'] == 'POST')
is the correct way, you can send a post request without any post data.
I used to check $_POST
until I got into a trouble with larger POST data and uploaded files. There are configuration directives post_max_size
and upload_max_filesize
- if any of them is exceeded, $_POST
array is not populated.
So the "safe way" is to check $_SERVER['REQUEST_METHOD']
. You still have to use isset()
on every $_POST
variable though, and it does not matter, whether you check or don't check $_SERVER['REQUEST_METHOD']
.
If your application needs to react on request of type post, use this:
if(strtoupper($_SERVER['REQUEST_METHOD']) === 'POST') { // if form submitted with post method
// validate request,
// manage post request differently,
// log or don't log request,
// redirect to avoid resubmition on F5 etc
}
If your application needs to react on any data received through post request, use this:
if(!empty($_POST)) { // if received any post data
// process $_POST values,
// save data to DB,
// ...
}
if(!empty($_FILES)) { // if received any "post" files
// validate uploaded FILES
// move to uploaded dir
// ...
}
It is implementation specific, but you a going to use both, + $_FILES superglobal.
You can submit a form by hitting the enter key (i.e. without clicking the submit button) in most browsers but this does not necessarily send submit as a variable - so it is possible to submit an empty form i.e. $_POST
will be empty but the form will still have generated a http post request to the php page. In this case if ($_SERVER['REQUEST_METHOD'] == 'POST')
is better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With