Skip to main content
  1. Posts/

How to use PHP cURL to make API calls in Wordpress

·747 words·4 mins·

Let’s learn how to use cURL in PHP (and, more specifically, in Wordpress) and why it is extremely simple.

Say you need to test that an endpoint of your API is working. Just curl it in your terminal and see the results. Say, for example, that you want to retrieve the info of a Github user with a single line:

curl https://api.github.com/users/defunkt

If only you could just copy and paste that curl request from the terminal to your PHP code.

Well, there is a way.

Why use cURL in WordPress?>

Why use cURL in WordPress? #

Say, for example that you need to add a contact to a MailChimp audience. You go to their documentation and see that they provide the following example of how to make a request with cURL from the terminal:

curl -X POST \
  'https://${dc}.api.mailchimp.com/3.0/lists/{list_id}/members?skip_merge_validation=<SOME_BOOLEAN_VALUE>' \
  --user "anystring:${apikey}"' \
  -d '{"email_address":"","email_type":"","status":"subscribed","merge_fields":{},"interests":{},"language":"","vip":false,"location":{"latitude":0,"longitude":0},"marketing_permissions":[],"ip_signup":"","timestamp_signup":"","ip_opt":"","timestamp_opt":"","tags":[]}'

All you need to do is replace some values, copy and paste it to your terminal. Press enter and you will get the response. Since it’s so straightforward, it usually works immediately. That’s all it takes to test that your request.

But now you have to translate this cURL request to a headers array and fit into a function like wp_remote_get(). Or maybe they ask you to install a dependency with Composer.

Yes, using curl was as simple as copy-paste the previous example. But if you want their sample snippet for PHP, this is what they give you:

<?php
require_once '/path/to/MailchimpMarketing/vendor/autoload.php';

$client = new MailchimpMarketing\ApiClient();
$client->setConfig([
    'apiKey' => 'YOUR_API_KEY',
    'server' => 'YOUR_SERVER_PREFIX',
]);

$response = $client->lists->addListMember("list_id", [
    "email_address" => "Lindsey.White93@hotmail.com",
    "status" => "pending",
]);
print_r($response);

This requires using Composer. If for any reason you don’t have Composer in your plugin/theme, this method could take you a lot of time.

If only you could just copy and paste that curl request from the terminal to your PHP code.

Well, there is a way.

How to use cURL in Wordpress with PHP>

How to use cURL in Wordpress with PHP #

The cURL command for PHP is the simplest way to translate a complex cURL request to PHP. Once you test it in your terminal and it works, all you need to do is translate it to PHP.

Now go to https://incarnate.github.io/curl-to-php/ and paste your working cURL request. It will translate it to PHP code. It’s that easy. Look at this example:

Untitled

Now you have the response from that curl request inside PHP in your $result variable.

How cURL sessions work in PHP>

How cURL sessions work in PHP #

Let’s see what this code returned by our translator means.

// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://us6.api.mailchimp.com/3.0/lists/5/members');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"email_address\":\"\",\"email_type\":\"\",\"status\":\"subscribed\",\"merge_fields\":{},\"interests\":{},\"language\":\"\",\"vip\":false,\"location\":{\"latitude\":0,\"longitude\":0},\"marketing_permissions\":[],\"ip_signup\":\"\",\"timestamp_signup\":\"\",\"ip_opt\":\"\",\"timestamp_opt\":\"\",\"tags\":[]}");
curl_setopt($ch, CURLOPT_USERPWD, 'anystring' . ':' . 'MY_APY_KEY'');

$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);

PHP cURL works by sessions. To create a cURL request, first we need to initiate a cURL session with curl_init(). For example, to create a session $ch, we do this:

$ch = curl_init();

Then we set every param with curl_setopt(). This function takes three arguments: your cURL session, the type of param, and the value of the param. Here is a list of all the params you can change with curl_setopt().

For example, if you want to set the contents of your POST request, you use the CURLOPT_POSTFIELDS and pass your json string as the third param.

curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"email_address\":\"email@email.com",\"tags\":[]}");

If you want to use basic authentication in your API call, just use CURLOPT_USERPWD option:

curl_setopt($ch, CURLOPT_USERPWD, 'anystring' . ':' . 'MY_APY_KEY'');

Finally, we execute that session using curl_exec(). It returns your result and takes your session as an argument, like this:

$result = curl_exec($ch);
Help, my request is returning true instead of the response data>

Help, my request is returning true instead of the response data #

By default, curl_exec() returns wither true (on successful request) or false. If you want it to return the returned data, you need to set the option CURLOPT_RETURNTRANSFER to true or 1.

Conclusion>

Conclusion #

This was how to use cURL requests in WordPress with PHP. Of course, it is always possible –and, most often, preferable– to use the WordPress native method for making API requests: wp_remote_get().

But if you are like me, you can often feel frustrated because your request already worked on the command line and you simple can’t get it to work in your code.