ad

Monday, 24 August 2015

Detect HTTP request type in PHP using $_SERVER array variable

$_SERVER is an array containing data such as HTTP headers, paths, and script locations. Basically server and execution environment information. This information is generated by your web server.

So if you var_dump($_SERVER), you will notice a big associate array where you can dig for specific information. So by using the array key 'REQUEST_METHOD', the method being used is returned.

You can either use if else statements or switch statements. Just provide it with method type variable and use case statements to take different actions upon different method types.

Here's a quick example.
switch ($method) { 
 case 'PUT': break; 
 case 'POST': break; 
 case 'GET': break; 
 }

Another basic way to check the HTTP method type is using the isset function with supergloabal variables(variables available in all scopes). Like $_POST or $_GET. So we end up with something like,
if(isset($_POST){
   //do this..
}






No comments:

Post a Comment