PHP: Detect if request type is POST or GET.

In this guide, we will show you how to detect the HTTP request type using PHP.

For example, is the user sending a GET or POST request? Or are they using another HTTP method such as PUT and DELETE?

Take a look at the following 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, PHP will store the HTTP request method in the $_SERVER array.

Therefore, you can easily access it by referencing the “REQUEST_METHOD” element.

Knowing the request type is useful for a number of reasons:

  1. You can restrict certain URLs to specific request types. If they fail to use the correct method, then you can respond with a 405 code. For example, if you have a page that receives form data, then 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.

Take a look at the following code, in which we handle different methods:

//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;
}

As you can see, PHP and its $_SERVER array make it pretty easy for us.