Search code examples
phpcurlput

How do I send a PUT request with JSON body with cURL?


I have this code to send a PUT request:

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_BODY, json_encode($result));

curl_exec($curl);

But that doesn't work, because CURLOPT_BODY does not exist. But, how do I add a body to my PUT request? I tried CURLOPT_POSTFIELDS, but that transforms my call into a POST (and I really do need a PUT).


Solution

  • cURL cannot inherently do a PUT request.

    You need to do the following:

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($result));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);