Doing PUT and DELETE with CURL in PHP

John Mertic —  August 30, 2013 — Leave a comment

As the new Web Services API relies more heavily on using HTTP verbs to work with records, the question came up on how to do this with PHP’s curl support. GET and POST are obvious here, but PUT and DELETE aren’t. Let’s look at some examples.

PHP curl has an extra setting for indicating a custom request type. So for DELETE, you could do this…

$curl = curl_init($url . "/Contacts/{$recordId}");
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json',"OAuth-Token: $token"));

// Make the REST call, returning the result
$response = curl_exec($curl);
if (!$response) {
    die("Connection Failure.n");
}

For PUT, I found this great article on the blog of a good friend of mine, Lorna Mitchell. PUT needs you to pass in a payload to the request, so this should work...

$curl = curl_init($url . "/Contacts/{$recordId}");
$data = array(
  'first_name' => 'John',
  );
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json',"OAuth-Token: $token"));
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));

// Make the REST call, returning the result
$response = curl_exec($curl);
if (!$response) {
    die("Connection Failure.n");
}

Hopefully this helps those of you using PHP curl get up and working with our new Web Services API.

John Mertic

Posts

John Mertic manages the strategic ISV alliances program for SugarCRM, having several years of techincal experience bringing solutions to market with several SugarCRM technology partners. A frequent conference speaker and an avid writer, he has been published in php|architect, IBM Developerworks, and in the Apple Developer Connection, and is the author of the book 'The Definitive Guide to SugarCRM: Better Business Applications' and the book 'Building on SugarCRM: Creating Applications the Easy Way'. He is also president of the OpenSocial foundation, guiding them in solving interoperability issues for enterprise application providers worldwide.

No Comments

Be the first to start the conversation!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s