1

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 -
Community
  • 1
  • 1
MouIdri
  • 1,300
  • 1
  • 18
  • 37

2 Answers2

3

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.

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • I got the "192.168.56.154 - - [04/May/2017 16:52:56] "PUT / HTTP/1.1" 404 -" on my target web server. I guess the issue comes from the command I sent. – MouIdri May 04 '17 at 15:57
  • are you sure you don't want to use `curl_setopt($ch, CURLOPT_POST, 1);` instead of `curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");` – Pedro Lobito May 04 '17 at 15:59
  • I edited my initial post. I confirm, I do not use : curl_setopt($ch, CURLOPT_POST, 1); Any clues ? – MouIdri May 04 '17 at 16:18
3

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

Machavity
  • 30,841
  • 27
  • 92
  • 100
  • That did the Job. thanks. I am messed up with the "array('data=start')"; I though I had to specify the type ( following other SO thread) but I guess I was wrong ! . Good to Know ! – MouIdri May 04 '17 at 16:37