Share via:

PHP: Checking the Request Method

It is sometimes useful to know the HTTP request method, and PHP makes this easy via the REQUEST_METHOD super global..


Edited: 2019-10-07 16:09

PHP article image

To check the request method you may use the $_SERVER['REQUEST_METHOD'] variable, the $_SERVER is a PHP Super Global that is available to you at any time, even inside functions and classes.

To use the REQUEST_METHOD variable you could just echo its contents, but it is probably more useful in a switch or if statement.

Quick example:

  echo 'The request was POST';
} else {
  $protocol = set_protocol();
  header($protocol . ' 400 Bad Request'); // Give an appropriate HTTP status
  echo 'Invalid request!';

Remember to determine the protocol the client is using before using header():

function set_protocol() {
  $supported_protocols = array(
    'HTTP/2.0' => true,
    'HTTP/1.1' => true,
    'HTTP/1.0' => true,
  $this->protocol = $_SERVER["SERVER_PROTOCOL"];
  if (!isset($supported_protocols["$protocol"])) {
    $protocol = 'HTTP/1.0';
  return $protocol;

The possible values are:

  1. GET
  2. HEAD
  3. POST
  4. PUT


The REQUEST_METHOD variable may be used whenever you need to determine the HTTP request type.

For example, if you know your application only accepts user input via HTTP post requests, it is recommended to block other types of requests, and inform the user that the request is not valid.

It can be used as part of the server-side validation of user input, before attempting to validate the input itself.