检测 PHP 中的请求类型(GET、POST、PUT 或 DELETE)

发布于 2024-07-10 07:35:43 字数 50 浏览 7 评论 0原文

如何检测 PHP 中使用了哪种请求类型(GET、POST、PUT 或 DELETE)?

How can I detect which request type was used (GET, POST, PUT or DELETE) in PHP?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

笔芯 2024-07-17 07:35:43

通过使用

$_SERVER['REQUEST_METHOD']

示例

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

了解更多详细信息,请参阅$_SERVER 变量的文档

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.

£冰雨忧蓝° 2024-07-17 07:35:43

PHP 中的 REST 可以非常简单地完成。 创建 http://example.com/test.php (概述如下)。 将其用于 REST 调用,例如 http://example.com/test.php/testing/ 123/你好。 这可以与 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;
}

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;
}
感性 2024-07-17 07:35:43

可以使用以下代码片段来检测 HTTP 方法或所谓的 REQUEST METHOD

$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
}

如果您更喜欢使用 switch 而不是 if-else 语句,也可以使用它。

如果 HTML 表单中需要 GETPOST 以外的方法,通常可以使用表单中的隐藏字段来解决。

<!-- 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>

有关 HTTP 方法的更多信息,我想参考以下 StackOverflow 问题:

HTTP协议的PUT和DELETE及其在PHP中的使用

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:

HTTP protocol's PUT and DELETE and their usage in PHP

冰雪之触 2024-07-17 07:35:43

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

$request = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);

We can also use the input_filter to detect the request method while also providing security through input sanitation.

$request = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);
时光磨忆 2024-07-17 07:35:43

您可以使用 getenv 函数,而不必使用 $_SERVER 变量:

getenv('REQUEST_METHOD');

更多信息:

http://php.net/manual/en/function.getenv.php

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

也只是曾经 2024-07-17 07:35:43

由于这是关于 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');

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');
北城半夏 2024-07-17 07:35:43

这很简单。 只需使用$_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;
}
?>

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;
}
?>
喜爱皱眉﹌ 2024-07-17 07:35:43

在核心 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;
}


?>

In core php you can do like this :

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


?>
淑女气质 2024-07-17 07:35:43

TL;DR

“true 的本机来源”是 $_SERVER 全局变量。 请求方法
保存在“REQUEST_METHOD”键下。

检查 $_SERVER 数组

$_SERVER['REQUEST_METHOD']

PHP 方法

但是您可以使用很多解决方法来获取方法。 像filter_input一样:
filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);


或者您使用外部库,例如:

  • Symfony\Component\HttpFoundation\Request
  • \Zend\Http\PhpEnvironment\Request

结论

但最简单的方法是使用: $ _SERVER['REQUEST_METHOD']

TL;DR

The "native source of true" is the $_SERVER global variable. The request Method
is saved under the key "REQUEST_METHOD".

Check the $_SERVER array

$_SERVER['REQUEST_METHOD']

PHP Methods

But you can use a lot of workarounds to get the Method. Like filter_input:
filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);

Libs
Or you use external libs like:

  • Symfony\Component\HttpFoundation\Request
  • \Zend\Http\PhpEnvironment\Request

Conclusion

But the easiest way would be to use: $_SERVER['REQUEST_METHOD'].

能否归途做我良人 2024-07-17 07:35:43
$request = new \Zend\Http\PhpEnvironment\Request();
$httpMethod = $request->getMethod();

这样在zend框架2中也可以实现。

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

In this way you can also achieve in zend framework 2 also.

浸婚纱 2024-07-17 07:35:43

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

上面回复中的方法是完全正确的,但是如果您想在处理 POSTDELETEPUT< 时额外检查 GET 参数/code>等请求,需要检查$_GET数组的大小。

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.

九歌凝 2024-07-17 07:35:43

当请求一个方法时,它将有一个数组。 因此,只需使用 count() 检查即可。

$m=['GET'=>$_GET,'POST'=>$_POST];
foreach($m as$k=>$v){
    echo count($v)?
    $k.' was requested.':null;
}

3v4l.org/U51TE

When a method was requested, it will have an array. So simply check with count().

$m=['GET'=>$_GET,'POST'=>$_POST];
foreach($m as$k=>$v){
    echo count($v)?
    $k.' was requested.':null;
}

3v4l.org/U51TE

风苍溪 2024-07-17 07:35:43

我用了这段代码。 它应该有效。

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>

I used this code. It should work.

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

This above code will work with REST calls and will also work with html form

<form method="post">
    <input name="_method" type="hidden" value="delete" />
    <input type="submit" value="Submit">
</form>
dawn曙光 2024-07-17 07:35:43

您可以获取任何查询字符串数据,即 www.example.com?id=2&name=r

您必须使用 $_GET['id']获取数据>$_REQUEST['id']

发布数据意味着像表单

一样,您必须使用 $_POST$_REQUEST

You can get any query string data i.e www.example.com?id=2&name=r

You must get data using $_GET['id'] or $_REQUEST['id'].

Post data means like form <form action='' method='POST'> you must use $_POST or $_REQUEST.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文