如何在PHP中获取PUT/DELETE参数。

12

我正在编写一个REST Web服务,并想知道如何在PHP中处理PUT或DELETE参数。

我将输入参数设置如下:

$input = file_get_contents('php://input');
echo $input;

输出 = imei=1234567890&email=hello%40gmail1.com

我如何访问这些变量?

echo $_POST['imei'];
echo $_POST['email'];
echo $_GET['imei'];
echo $_GET['email'];

我发现在PHP中没有像$_PUT或$_DELETE这样的东西来处理输入参数。那么获取它们的方式是什么?


你可以将它编码为JSON格式,然后作为JSON对象进行访问。 - Let me see
1
尝试使用这个 parse_str - StupidDev
1
$_SERVER['REQUEST_METHOD']: - Krish R
这个答案可能会有所帮助。请确保您的Web服务器支持PUT和DELETE请求,如果不支持,请尝试给出的解决方法。 - thesquaregroot
2个回答

14

你能试一下吗?PHP 没有内置的方法来做这件事,可以从传入的流中读取到 PHP,php://input

 parse_str(file_get_contents("php://input"),$post_vars);

例子:

  if($_SERVER['REQUEST_METHOD'] == 'GET') {
    echo "this is a get request\n";
    echo $_GET['fruit']." is the fruit\n";
    echo "I want ".$_GET['quantity']." of them\n\n";
} elseif($_SERVER['REQUEST_METHOD'] == 'PUT') {
    echo "this is a put request\n";
    parse_str(file_get_contents("php://input"),$post_vars);
    echo $post_vars['fruit']." is the fruit\n";
    echo "I want ".$post_vars['quantity']." of them\n\n";
}

参考:http://www.lornajane.net/posts/2008/accessing-incoming-put-data-from-php


1

不幸的是,php默认不处理put或delete请求。我创建了一个库来处理这种请求。它还处理多部分请求(PUT PATCH DELETE等)。

你可以在这里找到它 https://github.com/notihnio/php-request-parser


2
虽然我们喜欢回答中的链接,但由于链接过期后就失效了,因此我们通常不鼓励仅包含链接的回答。请更新您的回答,提供更多信息 :) - I.T Delinquent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接