PHP Curl Http Put

cURL with PHP passing data with PUT

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

Using PUT method with PHP cUrl Library

Instead of creating a temp file on disk you can use php://temp.

$body = 'the RAW data string I want to send';

/** use a max of 256KB of RAM before going to disk */
$fp = fopen('php://temp/maxmemory:256000', 'w');

if (!$fp)
{
die('could not open temp memory data');
}

fwrite($fp, $body);
fseek($fp, 0);

curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_INFILE, $fp); // file pointer
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body));

The upside is no disk IO so it should be faster and less load on your server.

Making a PUT request using CURL in PHP

I am only able to pass the array as a data with the versions I am using. So this is what I am doing now:

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_COOKIE, $curl_cookie);
$arr = array();
if (isset($data)) {
$arr['my_data'] = $data;
}

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($arr));
curl_exec($ch);

Why is PHP cURL PUT request not working despite getting status code 200 in return?

So far as I can see, you have two problems in your code.

  1. Content-Type: application/json is incorrect, I would remove it entirely.
  2. You don't have a Content-Length header.

I suggest trying

$sn = "123456789";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://example.com/api/sn/".$sn);

$data = array("cmd" => "clearUser");
$httpQuery = http_build_query($data);
$headers = array(
'Accept: application/json',
'Content-Length: ' . strlen($httpQuery)
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$username = 'XXX';
$password = 'XXX';
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,$httpQuery);

$output = curl_exec($ch);
curl_close($ch);


Related Topics



Leave a reply



Submit