PHP: Send a 405 Method Not Allowed header.

This is a short guide on how to send a 405 Method Not Allowed header with PHP. The 405 header allows us to tell the client that it has used an incorrect HTTP method. This is an important header to have in your toolbox if you intend on restricting PHP scripts to specific HTTP methods.

Let’s say that you want to restrict a PHP script to POST requests.

//An array of HTTP methods that
//we want to allow.
$allowedMethods = array(

//The current request type.
$requestMethod = strtoupper($_SERVER['REQUEST_METHOD']);

//If the request method isn't in our
//list of allowed methods.
if(!in_array($requestMethod, $allowedMethods)){
    //Send a 405 Method Not Allowed header.
    header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
    //Halt the script's execution.

//This will only be printed out if a
//POST request is used.
echo 'Hello world!';

In the PHP above, we:

  1. Created an array of HTTP methods that we want to allow. In the case above, we are only allowing POST requests. If we wanted to also allow PUT, HEAD or OPTIONS requests, we would simply add them to our $allowedMethods array.
  2. We retrieved the current request type by accessing the $_SERVER[‘REQUEST_METHOD’] variable.
  3. We checked to see if the the current request type is in our array of allowed HTTP methods.
  4. If the current HTTP method is not present in our $allowedMethods array, we send a 405 Method Not Allowed response to the client using PHP’s header function. We then kill the script using the exit statement.

If you attempt to navigate to this PHP script in your browser, you will see something like this:

405 error Chrome

An example of Chrome returning a 405 error.

This is because your browser sent a GET request to the page when the PHP script is only accepting POST requests.

Furthermore, if you inspect the response headers for the request in your browser’s developer tools, you will see something like this:

405 Method Not Allowed

As you can see, our PHP script has returned a 405 Method Not Allowed status code to the browser.

Using the http_response_code function to send a 405 error.

If you are using PHP version 5.4.0 or above, then you can use the http_response_code function. This function is a little more concise:

//Send a 405 Method Not Allowed header using http_response_code.
//Kill the script.

In the example above, we simply replaced the header function with the http_response_code function and passed in 405 as the $response_code parameter.

Related: Blocking POST requests with PHP.