Detecting request type in PHP (GET, POST, PUT or DELETE)

如何在PHP中检测使用哪种请求类型(GET,POST,PUT或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, eg 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 an 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

链接地址: http://www.djcxy.com/p/10026.html

上一篇: R中的数字比较难度

下一篇: 在PHP中检测请求类型(GET,POST,PUT或DELETE)