PHP: Send a 405 Method Not Allowed header.

In this article, we will show you how to send a “405 Method Not Allowed” header using PHP.

The “405” status allows us to tell a client it is using an incorrect HTTP method.

This is an important header to have in your “toolbox” if you want to restrict certain PHP scripts to POST, PUT, or GET requests.

For example, let’s say that we want to restrict a PHP script to POST requests only.

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

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

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

In the PHP code above:

  1. We create an array of HTTP methods that we want to allow. In this case, we only want to allow POST requests. If we also want to allow PUT, HEAD and OPTIONS requests, then we can add them to the array as well.
  2. We retrieve the current request type by accessing the $_SERVER[‘REQUEST_METHOD’] variable.
  3. After that, we check to see if 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. We do this by using PHP’s header function.
  5. Finally, we terminate the script.

If you attempt to navigate to this PHP script in your browser, you will see the following:

405 error Chrome

“This page isn’t working.” An example of Chrome returning a 405 error.

This is because your browser sent a GET request to the page when the PHP script only accepts 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.
http_response_code(405);
//Kill the script.
exit;

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.