In this guide, we are going to show you how to block POST requests using PHP.
This is particularly useful if you need to control which HTTP methods your scripts can accept on an application level.
Blocking POST requests and sending a “405 Method Not Allowed” header.
In the following code, we are 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.
- We detected the request method by retrieving the “REQUEST_METHOD” value from the $_SERVER superglobal array.
- We then checked to see if the request method was equal to “POST”.
- If it is a POST request, we send a “405 Method Not Allowed” header to the client and kill the script.
In many of the examples on Stack Overflow, people were simply killing the script without sending the 405 header.
The problem with this 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 making it clear to the client that the URL in question does not accept 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.
If you want to block or whitelist HTTP methods across your entire application, then you should probably do that on a server level.
For example, we recently wrote an article about blocking POST requests with a HAProxy load balancer.
You can also do something similar with Apache and Nginx.