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.

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:

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.

Facebook Comments