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.

php http request 

Nov 17

2 Answers

Its is quire easy to do : 

You can simply do this by using $_SERVER['REQUEST_METHOD']

    // Boom baby we a POST method
    // We are a GET method

answered Dec 02

PHP: Detect if request type is POST or GET.

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:


//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:

  1. Restrict HTTP requests to certain request types. i.e. If you have a page that allows a user to submit a comment, you might want to restrict that script to POST requests or PUT requests.
  2. It allows you to implement REST, which is a popular software architectural style that allows you to organize interactions between independent systems.

An example of handling different request methods in PHP:

//Get the request method.
$requestType = $_SERVER['REQUEST_METHOD'];

//Switch statement
switch ($requestType) {
    case 'POST':
    case 'GET':
    case 'DELETE':
      //request type that isn't being handled.

Pretty simple stuff!

answered Dec 30

Login and Submit Your Answer
Browse other questions tagged  php  http  request or ask your own question.