PHP: Block POST requests.

This is a short guide on how to block POST requests using PHP. This is particularly useful if you need to control what HTTP methods your scripts are accepting on an application level.

Blocking POST requests and sending a “405 Method Not Allowed” header.

In this example, I am specifically blocking POST requests:

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

//If the request method is POST.
if(strcasecmp($currentRequestMethod, 'POST') == 0){
    //Send a "405 Method Not Allowed" header to the client and kill the script
    header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
    exit;
}

In the example above:

  1. We detected the request method by retrieving the “REQUEST_METHOD” value from the $_SERVER superglobal array.
  2. We checked to see if the request method was equal to “POST”.
  3. If it is a POST request, we send a “405 Method Not Allowed” header to the client and kill the script.

In a lot of the examples that I saw on Stack Overflow, people were simply killing the script without sending the header. The problem with that approach is that the client is still receiving a “200 OK” response from the server. By sending the “405 Method Not Allowed” header, we are basically informing the client that the URL in question does not allow POST requests.

Allowing certain HTTP methods.

Another approach is to whitelist the HTTP methods that are allowed. Take the following example:

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

//A PHP array containing the methods that are allowed.
$allowedRequestMethods = array('GET', 'HEAD');

//Check to see if the current request method isn't allowed.
if(!in_array($currentRequestMethod, $allowedRequestMethods)){
    //Send a "405 Method Not Allowed" header to the client and kill the script
    header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
    exit;
}

In the script above, we check to see if the current request method is in our list of allowed methods. If it is not, then we send a 405 header to the client and exit the PHP script.

Note: If you want to whitelist HTTP methods across your entire application, then you should probably do that on a server level. For example, I recently wrote a post about blocking POST requests with a HAProxy load balancer. Similar approaches can also be taken with Apache and Nginx.

Anyway, I hope that this guide put you on the right track!