我怎么能检测到哪个请求类型被使用(GET, POST, PUT或删除)在PHP?


当前回答

$request = new \Zend\Http\PhpEnvironment\Request();
$httpMethod = $request->getMethod();

通过这种方式,您也可以在zend框架2中实现。 谢谢。

其他回答

因为这是关于REST的,所以仅仅从服务器获取请求方法是不够的。您还需要接收RESTful路由参数。分离RESTful参数和GET/POST/PUT参数的原因是资源需要有自己的唯一URL用于标识。

下面是使用Slim在PHP中实现RESTful路由的一种方法:

https://github.com/codeguy/Slim

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

并相应地配置服务器。

下面是另一个使用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');

通过使用

$_SERVER['REQUEST_METHOD']

例子

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

要了解更多细节,请参阅$_SERVER变量的文档。

$request = new \Zend\Http\PhpEnvironment\Request();
$httpMethod = $request->getMethod();

通过这种方式,您也可以在zend框架2中实现。 谢谢。

这是非常简单的使用$_SERVER['REQUEST_METHOD'];

例子:

<?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;
}
?>

PHP中的REST可以非常简单地实现。创建http://example.com/test.php(如下所示)。将此用于REST调用,例如http://example.com/test.php/testing/123/hello。这与Apache和Lighttpd一起开箱即用,不需要重写规则。

<?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;
}