I tried to write a script to let php do PUT request for me via CURLOPT_CUSTOMREQUEST, 'PUT'
for me but I kept receiving 422 error (it means the data is formatted wrong and cannot be processed).
First of, I tried direct sending out the PUT request in the terminal and postman, both works fine. The body of the request is a simple JSON format:
{"status":"online"}
Now, here are the code I tried:
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_HTTPHEADER => array( 'Authorization: "Panda is cute"' . "\r\n" . 'application/json; charset=utf-8' . "\r\n" . 'Content-Length: 19' . "\r\n" ),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => 'PUT',
CURLOPT_POST => false,
CURLOPT_POSTFIELDS => http_build_query( array ("status" => "online") )
));
$out = curl_exec($ch);
curl_close($ch);
echo $out;
I have tried a few modification of the code above.
- I tried
curl_setopt
everything instead of putting them all incurl_setopt_array
- I tried setting
CURLOPT_POST
to true. - I tried
CURLOPT_POSTFIELDS => json_encode( array ("status" => "online") )
- I tried
CURLOPT_POSTFIELDS => array ("status" => "online")
- I tried
CURLOPT_POSTFIELDS => '{"status":"online"}'
- I tried
CURLOPT_POSTFIELDS => 'http_build_query({"status":"online"})'
- I tried
CURLOPT_POSTFIELDS => 'http_build_query("status":"online")'
- I tried
json_encode
with the above two. - I also tried all of the above with
curl_setopt
. - I also tried to use
"
instead of my favorite'
everywhere I could, like where I wrote'PUT'
Now, when I use non-custom PUT request and upload a file it does work, but this is posting a challenge because my production environment won't allow me to do fopen()
.
P.S. Thanks for the answer below, and I know why it didn't work now:
CURLOPT_HTTPHEADER => array( 'Authorization: "Panda is cute"' . "\r\n" . 'application/json; charset=utf-8' . "\r\n" . 'Content-Length: 19' . "\r\n" )
This line will put an additional "\r\n"
at the end of the header (but without it php won't accept my original syntax and will post an error message, not rendering the header at all), making the content of my body "\r\n"{"status":"online"}
instead.