1002

How can I detect which request type was used (GET, POST, PUT or DELETE) in PHP?

YanDatsiuk
  • 1,355
  • 2
  • 15
  • 27
UnkwnTech
  • 79,308
  • 64
  • 178
  • 223

13 Answers13

1423

By using

$_SERVER['REQUEST_METHOD']

Example

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
     // The request is using the POST method
}

For more details please see the documentation for the $_SERVER variable.

Peter
  • 7,458
  • 6
  • 48
  • 87
gnud
  • 73,015
  • 5
  • 56
  • 76
  • 11
    What happens if you POST to mypage.php?var=something ? – nickf Dec 11 '08 at 12:21
  • 3
    The method will be POST, but if you have to use $_GET to get those variables Im not sure. – OIS Dec 11 '08 at 12:50
  • 2
    In the case nickf mentions, you could also (maybe) use the $_REQUEST variable. $_REQUEST contains post, get, and cookie values. Read the documentation at http://php.net/manual/en/reserved.variables.request.php – gnud Dec 11 '08 at 23:42
  • @nickf - the variable 'var' from your example will be in `$_POST['var']` – Nathan Long Mar 10 '10 at 16:48
  • If you just want to check if a form is posted, you can do simply `if (!empty($_POST)) {...`. Beware of `$_REQUEST` though! Careless usage of it adds a lot to CSRF kind of vulnerabilities. – Halil Özgür Dec 30 '10 at 16:20
  • @Paul Dixon print_r( $_SERVER ) is better for doing that :D – Salman von Abbas Apr 22 '11 at 12:43
  • 24
    @NathanLong In my experience that is incorrect. If you POST to mypage.php?var=something then 'something' will be in `$_GET['var']`. – David Gallagher Feb 07 '12 at 04:51
  • 18
    `$_POST` and `$_GET` are somewhat unfortunately named. `$_GET` contain variables from the URL's query component, regardless of the HTTP method. `$_POST` will contain form fields if the request was sent as `application/x-www-form-urlencoded`. – Pj Dietz Jul 23 '14 at 21:03
  • $_SERVER['REQUEST_METHOD'] what. what do we do with this? – Ahmed Syed Apr 17 '15 at 05:36
  • @MujahedAKAS you can check what method is used. It's a variable that contains the method used, i.e. 'GET', 'HEAD', 'POST', 'PUT'. So you can do a `if ($_SERVER['REQUEST_METHOD'] == 'POST'){ echo "POST received"}`. – PhoneixS Feb 03 '16 at 10:46
  • @gnud does we need `===`, what will happen if I used `==` ? – Kasun Siyambalapitiya Sep 06 '16 at 10:37
  • @Kasun You do not specifically *need* `===`, no. But there is no advantage in using `==`, and it is good practice to get accustomed to using the `===` absolutely *everywhere*. – Adowrath Feb 19 '18 at 11:47
229

REST in PHP can be done pretty simple. Create http://example.com/test.php (outlined below). Use this for REST calls, e.g. http://example.com/test.php/testing/123/hello. This works with Apache and Lighttpd out of the box, and no rewrite rules are needed.

<?php
$method = $_SERVER['REQUEST_METHOD'];
$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));

switch ($method) {
  case 'PUT':
    do_something_with_put($request);  
    break;
  case 'POST':
    do_something_with_post($request);  
    break;
  case 'GET':
    do_something_with_get($request);  
    break;
  default:
    handle_error($request);  
    break;
}
neu242
  • 14,861
  • 13
  • 69
  • 107
  • 20
    If you want to have your API available, without quoting what interpreting engine you're using, add a .htaccess file containing RewriteEngine on RewriteRule ^api/(.*)$ api.php/$1 This assumes your API file is called api.php. Also, since the above code block was written, the PHP developers have depreciated the split function. it works fine if you replace split with explode. – JonTheNiceGuy Jul 01 '10 at 11:55
  • 10
    What's with the `@` in front of `$_SERVER['PATH_INFO']`? – Svish Apr 19 '13 at 10:48
  • 10
    @Svish, what a great detail you noticed! It gets rid of `PHP Notice: Undefined index: PATH_INFO` in case PATH_INFO is not in `$_SERVER`. I'm adding this to my bag of tricks right away! It's a way of saying "I know there might not be an entry named that way in this array, and I'm ready for that, so just shut up and do what I tell you to". :) Thanks guys, both for posting this answer and for bringing my attention to that particular character in it. – inkredibl Jun 04 '13 at 12:24
  • 16
    I usually use a !empty instead of @. Better practice? – geilt Jul 18 '13 at 09:24
  • 8
    As a more concise way using variable methods: `` – SandWyrm Jul 31 '13 at 19:48
  • 1
    @Svish The @ is an error suppressor, and (from my translation) it means "Don't tell me when something is wrong Mr PHP, because I know better, and have thought of every possible eventuality and *know* nothing will be wrong which I will ever need to know about" (no offence neu242 :D) Write good code that won't have any PHP notices because of good code! – James Jun 16 '15 at 00:57
  • It is sunday morning and maybe I'm a bit dumb today, bur I cant get what is the use of $_SERVER['PATH_INFO'] when this variable is not set by Apache. I tried it and it returned empty! – Ed de Almeida Jul 26 '15 at 15:16
21

Detecting the HTTP method or so called REQUEST METHOD can be done using the following code snippet.

$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'POST'){
    // Method is POST
} elseif ($method == 'GET'){
    // Method is GET
} elseif ($method == 'PUT'){
    // Method is PUT
} elseif ($method == 'DELETE'){
    // Method is DELETE
} else {
    // Method unknown
}

You could also do it using a switch if you prefer this over the if-else statement.

If a method other than GET or POST is required in an HTML form, this is often solved using a hidden field in the form.

<!-- DELETE method -->
<form action='' method='POST'>
    <input type="hidden" name'_METHOD' value="DELETE">
</form>

<!-- PUT method -->
<form action='' method='POST'>
    <input type="hidden" name'_METHOD' value="PUT">
</form>

For more information regarding HTTP methods I would like to refer to the following StackOverflow question:

HTTP protocol's PUT and DELETE and their usage in PHP

mujuonly
  • 6,482
  • 5
  • 30
  • 59
Peter
  • 7,458
  • 6
  • 48
  • 87
12

You can use getenv function and don't have to work with a $_SERVER variable:

getenv('REQUEST_METHOD');

More info:

http://php.net/manual/en/function.getenv.php

Artegon
  • 2,734
  • 6
  • 32
  • 62
12

We can also use the input_filter to detect the request method while also providing security through input sanitation.

$request = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);
HelpNeeder
  • 5,933
  • 21
  • 80
  • 141
9

Since this is about REST, just getting the request method from the server is not enough. You also need to receive RESTful route parameters. The reason for separating RESTful parameters and GET/POST/PUT parameters is that a resource needs to have its own unique URL for identification.

Here's one way of implementing RESTful routes in PHP using Slim:

https://github.com/codeguy/Slim

$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
  echo "Hello, $name";
});
$app->run();

And configure the server accordingly.

Here's another example using AltoRouter:

https://github.com/dannyvankooten/AltoRouter

$router = new AltoRouter();
$router->setBasePath('/AltoRouter'); // (optional) the subdir AltoRouter lives in

// mapping routes
$router->map('GET|POST','/', 'home#index', 'home');
$router->map('GET','/users', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', 'users_show');
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');
nurettin
  • 9,834
  • 5
  • 53
  • 77
6
$request = new \Zend\Http\PhpEnvironment\Request();
$httpMethod = $request->getMethod();

In this way you can also achieve in zend framework 2 also. Thanks.

Amit Patange
  • 167
  • 2
  • 12
6

It is Very Simple just use $_SERVER['REQUEST_METHOD'];

Example:

<?php
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
  case 'GET':
    //Here Handle GET Request 
    break;
  case 'POST':
    //Here Handle POST Request 
    break;
  case 'DELETE':
    //Here Handle DELETE Request 
    break;
  case 'PUT':
    //Here Handle PUT Request 
    break;
}
?>
Juned Ansari
  • 4,161
  • 3
  • 43
  • 70
  • 1
    The "DELETE" case will never be hit because that's not a possible REQUEST_METHOD. The valid REQUEST_METHODs are 'GET', 'HEAD', 'POST', 'PUT'. Read the documentation (pointed to in numerous answers on this very page) before posting an answer. – Patrick Apr 16 '17 at 08:42
  • 1
    @Patrick, actually, the "DELETE" case will get a hit when the request method is DELETE; nonetheless the documentation in PHP does not mention it. Indeed, any method gets reflected in `$_SERVER['REQUEST_METHOD']`, even customized ones. Remember that the method is just a string in the request header and that it is our task to check for its correctness. – Ivan De Paz Centeno May 01 '17 at 18:36
  • 1
    @Patrick DELETE is defined in RFC7231 and is supported in all major browsers. https://tools.ietf.org/html/rfc7231#section-4.3.5 and $_SERVER["REQUEST_METHOD"] is just a string. – Robert Talada May 16 '19 at 03:32
  • @IvanDePazCenteno Exactly. Never trust user input. Never trust user input. – Robert Talada May 16 '19 at 03:33
4

In core php you can do like this :

<?php

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
  case 'GET':
    //Here Handle GET Request
    echo 'You are using '.$method.' Method';
    break;
  case 'POST':
    //Here Handle POST Request
    echo 'You are using '.$method.' Method';
    break;
  case 'PUT':
    //Here Handle PUT Request
    echo 'You are using '.$method.' Method';
    break;
  case 'PATCH':
    //Here Handle PATCH Request
    echo 'You are using '.$method.' Method';
    break;
  case 'DELETE':
    //Here Handle DELETE Request
    echo 'You are using '.$method.' Method';
    break;
  case 'COPY':
      //Here Handle COPY Request
      echo 'You are using '.$method.' Method';
      break;

  case 'OPTIONS':
      //Here Handle OPTIONS Request
      echo 'You are using '.$method.' Method';
      break;
  case 'LINK':
      //Here Handle LINK Request
      echo 'You are using '.$method.' Method';
      break;
  case 'UNLINK':
      //Here Handle UNLINK Request
      echo 'You are using '.$method.' Method';
      break;
  case 'PURGE':
      //Here Handle PURGE Request
      echo 'You are using '.$method.' Method';
      break;
  case 'LOCK':
      //Here Handle LOCK Request
      echo 'You are using '.$method.' Method';
      break;
  case 'UNLOCK':
      //Here Handle UNLOCK Request
      echo 'You are using '.$method.' Method';
      break;
  case 'PROPFIND':
      //Here Handle PROPFIND Request
      echo 'You are using '.$method.' Method';
      break;
  case 'VIEW':
      //Here Handle VIEW Request
      echo 'You are using '.$method.' Method';
      break;
  Default:
    echo 'You are using '.$method.' Method';
  break;
}


?>
Shaan Ansari
  • 343
  • 2
  • 9
1

It is valuable to additionally note, that PHP will populate all the $_GET parameters even when you send a proper request of other type.

Methods in above replies are completely correct, however if you want to additionaly check for GET parameters while handling POST, DELETE, PUT, etc. request, you need to check the size of $_GET array.

Karol Sobański
  • 289
  • 2
  • 12
0

When a method was requested, it will have an array. So simply check with count().

$m=['GET'=>$_GET,'POST'=>$_POST];
foreach($m as$k=>$v){
    echo count($v)?
    $k.' was requested.':null;
}

3v4l.org/U51TE

Thielicious
  • 3,054
  • 2
  • 22
  • 31
0

I used this code. It should work.

function get_request_method() {
    $request_method = strtolower($_SERVER['REQUEST_METHOD']);

    if($request_method != 'get' && $request_method != 'post') {
        return $request_method;
    }

    if($request_method == 'post' && isset($_POST['_method'])) {
        return strtolower($_POST['_method']);
    }

    return $request_method;
}

This above code will work with REST calls and will also work with html form

<form method="post">
    <input name="_method" type="hidden" value="delete" />
    <input type="submit" value="Submit">
</form>
mahfuz
  • 1,042
  • 10
  • 16
-6

You can get any query string data i.e www.example.com?id=2&name=r

You must get data using $_GET['id'] or $_REQUEST['id'].

Post data means like form <form action='' method='POST'> you must use $_POST or $_REQUEST.

Huey
  • 4,654
  • 6
  • 30
  • 43