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..

135 views

Edited: 2019-11-06 20:24

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.

Some possible values are:

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

Quick example:

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

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,
  );
  $protocol = $_SERVER["SERVER_PROTOCOL"];
  if (!isset($supported_protocols["$protocol"])) {
    $protocol = 'HTTP/1.0';
  }
  return $protocol;
}

When to use REQUEST_METHOD

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.

The REQUEST_METHOD variable is filled out by PHP based on the HTTP request type, and can therefor be safely used without validation. There should be no risk of injection attacks in this variable.

We can not simply check if $_POST and $_GET is empty, since they are always defined, even if all the HTML form fields are empty.

Links

  1. HTTP GET and POST Methods
  2. $_POST and $_GET is Always Defined

Comments