No PUT post data being received

こ雲淡風輕ζ 提交于 2019-12-11 14:46:56

问题


I am sending out a PUT request to my site via PHP using cURL:

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

I am then listening for this PUT request, but receiving no data with the request. Please can you tell me where I am going wrong?

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

回答1:


make sure to specify a content-length header and set post fields as a string

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


Use an HTTP client class to help send the requests. There are several available, but I have created one (https://github.com/broshizzledizzle/Http-Client) that I can give you help with.

Making a PUT request:

<?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();

?>

Processing a PUT request:

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

        break;
}

Note that I have an autoloader on my projects that will load all those includes for me, but you may want to consider making a file that will include everything if you don't want to go down that route.


Library-less:

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

Note that you use a stream to send the data.



来源:https://stackoverflow.com/questions/8069737/no-put-post-data-being-received

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!