tags:

views:

7945

answers:

2

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

+41  A: 

By using

$_SERVER['REQUEST_METHOD']
gnud
+1 to that - when in doubt, var_dump($_SERVER) and the answer often lies within.
Paul Dixon
True but a google search didn't turn up any results, and now within a day or two it will. ;)
Unkwntech
What happens if you POST to mypage.php?var=something ?
nickf
The method will be POST, but if you have to use $_GET to get those variables Im not sure.
OIS
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
@nickf - the variable 'var' from your example will be in `$_POST['var']`
Nathan Long
http://php.net/manual/en/reserved.variables.server.php
Xiong Chiamiov
+6  A: 

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 = split("/", substr(@$_SERVER['PATH_INFO'], 1));

switch ($method) {
  case 'PUT':
    rest_put($request);  
    break;
  case 'POST':
    rest_post($request);  
    break;
  case 'GET':
    rest_get($request);  
    break;
  case 'HEAD':
    rest_head($request);  
    break;
  case 'DELETE':
    rest_delete($request);  
    break;
  case 'OPTIONS':
    rest_options($request);    
    break;
  default:
    rest_error($request);  
    break;
}
?>
neu242
If you want to have your API available, without quoting what interpreting engine you're using, add a .htaccess file containingRewriteEngine onRewriteRule ^api/(.*)$ api.php/$1This 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