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:

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

  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':
      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!