Asked : Nov 17
Viewed : 63 times
How can I detect which request type was used (GET, POST, PUT or DELETE) in PHP?
I researched for this and find that I can do this with $_SERVER
but I do not know how to use this.
Please give me some examples of this too.
Thank You.
Nov 17
Its is quire easy to do :
You can simply do this by using $_SERVER['REQUEST_METHOD']
.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Boom baby we a POST method
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// We are a GET method
}
answered Dec 02
This is a simple guide on how to detect the request type with PHP. i.e. Is the user making a POST request or a GET request – or are they using one of the other HTTP methods, such as PUT and DELETE.
Here is a simple example:
<?php
//Get the request method from the $_SERVER
$requestType = $_SERVER['REQUEST_METHOD'];
//Print the request method out on to the page.
echo $requestType;
As you can see, the request method is accessible via the $_SERVER array.
Obviously, knowing the request type is handy, as it allows you to:
An example of handling different request methods in PHP:
//Get the request method.
$requestType = $_SERVER['REQUEST_METHOD'];
//Switch statement
switch ($requestType) {
case 'POST':
handle_post_request();
break;
case 'GET':
handle_get_request();
break;
case 'DELETE':
handle_delete_request();
break;
default:
//request type that isn't being handled.
break;
}
Pretty simple stuff!
answered Dec 30