I am trying to create a HTTP PUT request with cURL and I can't make it work. I've read many tutorials but none of them actually worked. Here's my current code:
$filedata = array('metadata' => $rdfxml);
$ch = curl_init($url);
$header = "Content-Type: multipart/form-data; boundary='123456f'";
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($filedata));
$returned = curl_exec($ch);
if (curl_error($ch))
{
print curl_error($ch);
}
else
{
print 'ret: ' .$returned;
}
I've also tried using PHP PEAR but got the same result. The problem is that the repository says that no metadata has been set. I really need help! Thanks!
You have mixed 2 standard.
The error is in $header = "Content-Type: multipart/form-data; boundary='123456f'";
The function http_build_query($filedata)
is only for "Content-Type: application/x-www-form-urlencoded", or none.
In a POST method, you can put an array. However, in a PUT method, you should use http_build_query
to build the params like this:
curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $postArr ) );
Using Postman for Chrome, selecting CODE you get this... And works
<?php_x000D_
_x000D_
$curl = curl_init();_x000D_
_x000D_
curl_setopt_array($curl, array(_x000D_
CURLOPT_URL => "https://blablabla.com/comorl",_x000D_
CURLOPT_RETURNTRANSFER => true,_x000D_
CURLOPT_ENCODING => "",_x000D_
CURLOPT_MAXREDIRS => 10,_x000D_
CURLOPT_TIMEOUT => 30,_x000D_
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,_x000D_
CURLOPT_CUSTOMREQUEST => "PUT",_x000D_
CURLOPT_POSTFIELDS => "{\n \"customer\" : \"con\",\n \"customerID\" : \"5108\",\n \"customerEmail\" : \"[email protected]\",\n \"Phone\" : \"34600000000\",\n \"Active\" : false,\n \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",_x000D_
CURLOPT_HTTPHEADER => array(_x000D_
"cache-control: no-cache",_x000D_
"content-type: application/json",_x000D_
"x-api-key: whateveriyouneedinyourheader"_x000D_
),_x000D_
));_x000D_
_x000D_
$response = curl_exec($curl);_x000D_
$err = curl_error($curl);_x000D_
_x000D_
curl_close($curl);_x000D_
_x000D_
if ($err) {_x000D_
echo "cURL Error #:" . $err;_x000D_
} else {_x000D_
echo $response;_x000D_
}_x000D_
_x000D_
?>
_x000D_
Just been doing that myself today... here is code I have working for me...
$data = array("a" => $a);
$ch = curl_init($url);
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);
if (!$response)
{
return false;
}
src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl
Source: Stackoverflow.com