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


当前回答

值得注意的是,即使您发送了其他类型的请求,PHP也会填充所有的$_GET参数。

上述回复中的方法是完全正确的,但是如果你想在处理POST, DELETE, PUT等请求时额外检查GET参数,你需要检查$_GET数组的大小。

其他回答

我们还可以使用input_filter来检测请求方法,同时通过输入环境保护来提供安全性。

$request = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);
$request = new \Zend\Http\PhpEnvironment\Request();
$httpMethod = $request->getMethod();

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

我使用了这个代码。它应该会起作用。

function get_request_method() {
    $request_method = strtolower($_SERVER['REQUEST_METHOD']);

    if($request_method != 'get' && $request_method != 'post') {
        return $request_method;
    }

    if($request_method == 'post' && isset($_POST['_method'])) {
        return strtolower($_POST['_method']);
    }

    return $request_method;
}

上面的代码将与REST调用一起工作,也将与html表单一起工作

<form method="post">
    <input name="_method" type="hidden" value="delete" />
    <input type="submit" value="Submit">
</form>

在core php中,你可以这样做:

<?php

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
  case 'GET':
    //Here Handle GET Request
    echo 'You are using '.$method.' Method';
    break;
  case 'POST':
    //Here Handle POST Request
    echo 'You are using '.$method.' Method';
    break;
  case 'PUT':
    //Here Handle PUT Request
    echo 'You are using '.$method.' Method';
    break;
  case 'PATCH':
    //Here Handle PATCH Request
    echo 'You are using '.$method.' Method';
    break;
  case 'DELETE':
    //Here Handle DELETE Request
    echo 'You are using '.$method.' Method';
    break;
  case 'COPY':
      //Here Handle COPY Request
      echo 'You are using '.$method.' Method';
      break;

  case 'OPTIONS':
      //Here Handle OPTIONS Request
      echo 'You are using '.$method.' Method';
      break;
  case 'LINK':
      //Here Handle LINK Request
      echo 'You are using '.$method.' Method';
      break;
  case 'UNLINK':
      //Here Handle UNLINK Request
      echo 'You are using '.$method.' Method';
      break;
  case 'PURGE':
      //Here Handle PURGE Request
      echo 'You are using '.$method.' Method';
      break;
  case 'LOCK':
      //Here Handle LOCK Request
      echo 'You are using '.$method.' Method';
      break;
  case 'UNLOCK':
      //Here Handle UNLOCK Request
      echo 'You are using '.$method.' Method';
      break;
  case 'PROPFIND':
      //Here Handle PROPFIND Request
      echo 'You are using '.$method.' Method';
      break;
  case 'VIEW':
      //Here Handle VIEW Request
      echo 'You are using '.$method.' Method';
      break;
  Default:
    echo 'You are using '.$method.' Method';
  break;
}


?>

这是非常简单的使用$_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;
}
?>