【问题标题】:No PUT post data being received未收到 PUT 发布数据
【发布时间】:2011-12-25 13:34:27
【问题描述】:

我正在使用 cURL 通过 PHP 向我的网站发送 PUT 请求:

$data = array("a" => 'hello');
$ch = curl_init('http://localhost/linetime/user/1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

$response = curl_exec($ch);
var_dump($response);

然后,我正在侦听此 PUT 请求,但没有收到该请求的任何数据。请问你能告诉我哪里出错了吗?

$putData = '';
$fp = fopen('php://input', 'r');
while (!feof($fp)) {
    $s = fread($fp, 64);
    $putData .= $s;
}
fclose($fp);
echo $putData;
exit;

【问题讨论】:

  • 您的意思是您在 Web 服务器的配置中将您的脚本指定为 PUT 处理程序?例如在 Apache 中使用 Script 指令:Script PUT /your/script.php
  • 尝试强制使用Content-Length 标头。
  • @XcodeDev 请参阅下面我更新的帖子。我认为问题在于您发送数据的方式,而不是您接收数据的方式。

标签: php post curl put


【解决方案1】:

确保指定内容长度标头并将帖子字段设置为字符串

$data = array("a" => 'hello');    
$fields = http_build_query($data)
$ch = curl_init('http://localhost/linetime/user/1');

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); 

//important
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields))); 

curl_setopt($ch, CURLOPT_POSTFIELDS,$fields); 

【讨论】:

  • 感谢您的帖子,我仍然遇到同样的问题!
【解决方案2】:

使用 HTTP 客户端类来帮助发送请求。有几个可用的,但我创建了一个 (https://github.com/broshizzledizzle/Http-Client) 可以为您提供帮助。

发出 PUT 请求:

<?php
require_once 'Http/Client.php';
require_once 'Http/Method.php';
require_once 'Http/PUT.php';
require_once 'Http/Request.php';
require_once 'Http/Response.php';
require_once 'Http/Uri.php';

use Http\Request;
use Http\Response;

header('Content-type:text/plain');

    $client = new Http\Client();


    //GET request
    echo $client->send(
        Request::create()
            ->setMethod(new Http\PUT())
            ->setUri(new Http\Uri('http://localhost/linetime/user/1'))
            ->setParameter('a', 'hello')
    )->getBody();

?>

处理 PUT 请求:

//simply print out what was sent:
switch($_SERVER['REQUEST_METHOD']) {
    case 'PUT':
        echo file_get_contents('php://input');

        break;
}

请注意,我的项目中有一个自动加载器,它将为我加载所有这些包含,但如果您不想走这条路,您可能需要考虑制作一个包含所有内容的文件。


无库:

//initialization code goes here

$requestBody = http_build_query(
    array('a'=> 'hello'),
    '',
    '&'
);

$fh = fopen('php://memory', 'rw');
fwrite($fh, $requestBody);  
rewind($fh); 

curl_setopt($this->curl, CURLOPT_INFILE, $fh);  
curl_setopt($this->curl, CURLOPT_INFILESIZE, strlen($requestBody));  
curl_setopt($this->curl, CURLOPT_PUT, true); 

//send request here

fclose($fh);

请注意,您使用流来发送数据。

【讨论】:

  • 不,不是。刚刚测试:代码在我的系统上运行,虽然它不使用 file_get_contents 很笨重。
  • 会不会是因为我用的是MAMP?
  • curl 请求运行良好,但在请求的另一端我仍然没有收到任何数据。
  • @XcodeDev 尝试使用上面更新的代码。我已经验证它在本地主机上对我自己有效。
  • @XcodeDev 然后你没有向 PHP 发送任何输入。这可能是因为您没有按照应有的方式向 PHP 发送流。在没有库的情况下发布了一些 PHP 代码。
猜你喜欢
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
相关资源
最近更新 更多