You are here: / Articles / Guides / Programming / Technology / You can Detect the HTTP Request Method Using PHP by Doing This

You can Detect the HTTP Request Method Using PHP by Doing This

HTTP Request Method

Share!



This is another beginner PHP article this time focusing on how to detect the HTTP request method. If you are a more competent developer then you might want to jump onto another article. How about this one on how to get both GET and POST methods in one request.

Why the Interest in Detecting the HTTP Request Method

Back to the point of this guide. The most compelling answer to this is, it is all about security. We know there are more that one request methods when web browsers respond to servers. You, the developer may want to restrict your processes to certain response types.

These are also important when building code such as REST APIs.

A simple example would be to receive passwords from an HTML form via the POST method only. To be able to handle this feature you need to know how to detect the correct HTTP request method.

Read Also  Moringa Oleifera, Secrets of the Drumstick Tree

The simple solution is to check the request method using:

$_SERVER['REQUEST_METHOD']

A simple use case would look something like this:

if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
// Do something because the request method is POST
}
else {
// Abort whatever
}

The above method does not bode well from a security standpoint. The input here has not been validated nor sanitized. One way to fix this is to use the built in filter_input PHP function. The above code would look something like this now:

$request_method = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);

if ( $request_method === ‘POST’ ) {
// Do something because the request method is POST
}
else {
// Abort whatever
}

If you want to test and handle different request methods differently, a more elegant way would be to use the PHP built-in switch statement. Here is a good example to start with. It also shows the supported HTTP request methods:

That’s it. There is not much to this but with these simple tips, you are now on your way to handling better code in terms of readability and security. Furthermore, you are now past the first hurdle to building your very own REST API.