没有PUT发布数据被接收

时间:2011-11-09 18:29:06

标签: php post curl put

我使用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;

2 个答案:

答案 0 :(得分:2)

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

$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); 

答案 1 :(得分:0)

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

请注意,我的项目中有一个自动加载器,可以为我加载所有这些内容,但是如果您不想沿着这条路线行进,您可能需要考虑制作一个包含所有内容的文件。 / em>的


<强>库少:

//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);

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