Main menu

PUTting data fields with PHP cURL

This is a little post about how to PUT multiple data fields using the PHP cURL extension. Why I wanted to do this in the first place is beyond the scope of this post, since its quite a long story. The curl command line allows data fields to be sent with a PUT request, and I wanted to do the same from PHP. Here is a snippet of code to show how I did it.

Brilliant!!! I'd been looking high and low for a SIMPLE example of using PUT with CURL in PHP but none of the examples worked or were way too complex for my needs. This little snipped of code was exactly what I needed to get some of my own code working :)

Different services may need all kinds of different headers, and you can set them using this CURLOPT_HTTPHEADER as shown here. I haven't seen that one before, but there are similar "features" in many APIs. Thanks for taking the time to add the code example.

Thank you so much for posting this. I've been banging my head against this issue for several hours.
Seems crazy that
[code]curl_setopt($ch, CURLOPT_PUT, true);[/code]
and
[code]curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");[/code]
should produce identical results ... but somehow the first one doesn't work and the second one does.

In reply to Andy's comment, I think you can get CURLOPT_PUT to work if you provide the data using INFILE instead of POSTFIELDS. For example:
[code]
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $putData);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString));
[/code]
I would guess the reason is that POST can be used with either form data or a payload, but using PUT with form data doesn't make sense.