The REQUEST_METHOD superglobal in PHP

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

4324 views
d

By. Jacob

Edited: 2021-05-21 07:36

PHP article image

To check the request method you may use the $_SERVER['REQUEST_METHOD'] variable, the $_SERVER is a PHP superglobal 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.

Request types:

Example:

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  echo 'The request was POST';
  exit();
} else {
  http_response_code(405);
  header('Allow: GET, HEAD');
  echo '<h1>405 Method Not Allowed</h1>';
  exit();
}

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

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials