Search code examples
phpcurlput

cURL with PHP passing data with PUT


I would like to curl thru PHP using PUT method to a remote server. And stream to a file.

My normal command would look like this :

curl http://192.168.56.180:87/app -d "data=start" -X PUT 

I saw this thread on SO .

EDIT :

Using Vitaly and Pedro Lobito comments I changed my code to :

$out_file = "logging.log";
$fp = fopen($out_file, "w");

$ch = curl_init();
$urlserver='http://192.168.56.180:87/app';
$data = array('data=start');
$ch = curl_init($urlserver);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

curl_exec($ch);
curl_close($ch);
fclose($fp);

But still not Ok.

When My I have this response using curl :

 192.168.56.154 - - [04/May/2017 17:14:55] "PUT /app HTTP/1.1" 200 -

And I have this response using the php above:

 192.168.56.154 - - [04/May/2017 17:07:55] "PUT /app HTTP/1.1" 400 -

Solution

  • You're passing the POST string incorrectly

    $data = array('data=start');
    curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
    

    In this case, you've already built your string, so just include it

    $data = 'data=start';
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    

    http_build_query is only when you have a key => value array and need to convert it to a POST string