How can I detect which request type was used (GET, POST, PUT or DELETE) in PHP?
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');
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;
}
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.
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;
}
?>
By using
$_SERVER['REQUEST_METHOD']
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// The request is using the POST method
}
For more details please see the documentation for the $_SERVER variable.
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