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.

        $data = array("a" => $a);
        $ch = curl_init($this->_serviceUrl . $id);
 
        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;
        }

I'm putting this here so I remember for next time - if it helps you as well then even better :)

23 thoughts on “PUTting data fields with PHP cURL

  1. Pingback: SugarCRM Developer Blog » Blog Archive » HOWTO: Do PUT requests with PHP cURL without writing to a file

  2. You finally gave me the answer I was looking for with PUT variables - http_build_query(). Simple answer yet so hard to find! Thanks!

  3. 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 :)

    Many thanks for sharing...

    • 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.

    • Sorry, I'm not sure how to help since these examples worked for me. Perhaps you can log a ticket with your API provider? Good luck!

  4. Pingback: cURL PUT vs Zend_Rest_Controller - Zend Framework Forum - ZF1 / ZF2

  5. Many Many And Many Thanks, for this articles. it's simple and also very helpful..

    Thanks for this Post..

    Have a good day..

  6. Pingback: SugarCRM Developer Blog » Blog Archive » Doing PUT and DELETE with CURL in PHP

  7. Pingback: Doing PUT and DELETE with CURL in PHP « SugarCRM Developer Blog

  8. How would one change your script to send an XML file; your code seems to be building the http_post code
    Any help will be appreciated

    By the way a grat write up..

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>