Detecting request type in PHP (GET, POST, PUT or DELETE)
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.
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;}
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: