Client URL Library (cURL) – An Overview

What is cURL?

Client URL Library or cURL for short is a library of functions designed for the purpose of safely fetching information from remote sites.  The purpose of the library is to send a request to a server using a defined protocol (http, https, ftp, etc) and to return the result back to you for usage in your application or script.

How do I use cURL?

Using cURL is a simple 4 or 5 step process depending on your needs.

  1. Initate a cURL session utilizing curl_init(). This function returns a session handler that you will use for manipulation the request.
    $ch = curl_init("http://www.example.com/");
  2. Set your options for the request utilizing the curl_setopt() function. You can either set these options one at a time or pass an associated array that contains all your options. Complete options can be found at the php.net curl_setopt page but a few basic ones are:
    • CURLOPT_RETURNTRANSFER
      determines if the result should be outputted as string or directly
    • CURLOPT_SSL_VERIFYHOST
      determines if the host’s SSL Certificate should be verified
    • CURLOPT_POST
      set the request to use HTTP POST protocol
    • CURLOPT_POSTFIELDS
      set the post parameters to be sent with the request
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  3. Execute the cURL request and if using return transfer as string then set it to a variable.
    $resp = curl_exec($ch)
  4. This is the optional step in that you can obtain information about the request you just performed. One of the main usages is to return the HTTP_CODE that was returned to determine if the request was successfull or if there was an error. To do this you utilize the curl_getinfo() function, full documentation can be found on the php.net curl_getinfo page.
    $code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
  5. Finally once completed you will want to close your session to free up resources. This is done by using the curl_close() function.
    curl_close($ch);

Summary

Utilizing the cURL library in your application to talk to remote servers allows you to easily interact with available APIs that are provided by Harvest, Google Analtyics and others. In addition it provides security to your application as you are not running any external scripts on your server only sending a request and obtaining its output.

// PHP //

Comments & Questions

Add Your Comment