'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 1:[1]
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
Solution 2:[2]
Why don't you save the curl output directly to a file? i.e.:
$out_file = "/path/to/file";
$fp = fopen($out_file, "w");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec($ch);
fclose($fp);
curl_close($ch);
Note:
When you ask a question about an error, always include the error log. To enable error reporting, add error_reporting(E_ALL); ini_set('display_errors', 1); at the top of your php script.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Machavity |
| Solution 2 |
