August 22, 2017 231 Views 1 Comment

Using PHP CURL to communicate with REST based APIs

SHARE THIS ARTICLE
With the growing popularity of REST based API’s, it is very important for web developers to be able to quickly integrate and establish secure communication channels between apps. One very clean and efficient way to pass requests to any REST based API is through PHP’s CURL functon. Let’s look at how to utilize this function.

What is CURL
Curl is a library that lets you make HTTP requests in PHP.

How do I use CURL in my PHP Project
Here’s a function to get you started. Before using make sure that your server has libcurl installed.


function CallCURL($method, $url, $data = false){
        $curl = curl_init();
        switch ($method){
            case "POST":
                curl_setopt($curl, CURLOPT_POST, 1);

                if ($data)
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                break;
            case "PUT":
                curl_setopt($curl, CURLOPT_PUT, 1);
                break;
            default:
                if ($data)
                    $url = sprintf("%s?%s", $url, http_build_query($data));
        }

        // Optional Authentication:
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($curl, CURLOPT_USERPWD, "username:password");

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //setting content type and Accept JSON headers        
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json'));

        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

//Call function
print_r(CallAPI("POST", "http://some-api-url/v1/books", $data));
  • guest

    One small edit there, for “PUT” request use:
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, “PUT”);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

    Works great, thanks for sharing!