How to Use PHP/cURL - The Basics

cURL is a powerful tool for transferring data across various protocols like http, ftp, gopher, file telnet among others. PHP provides support for cURL through the libcurl library as made available through the php_curl extension. In order to make use of the following tutorial, you need to have PHP on your server and it's php_curl extension enabled (enabled by most webhosts).

Is there an easier way to do all this?

I'd like to point out that while cURL may be the best way carry out data transfer across protocols in PHP, that does not mean it is the easiest or most efficient.
If you're looking for an easier and safer way to perform HTTP requests, I'd recommend checking out Guzzle.

cURL Basic Usage

<?php

//initialize cURL Session - create resource
$curl_handle = curl_init();

// Setting up a single curl option (curl_setopt)
curl_setopt($curl_handle, CURLOPT_URL, "https://php.net");
curl_setopt($curl_handle, CURLOPT_VERBOSE, true);

// (OR) Setting up mutiple options (curl_setopt_array)
curl_setopt_array($curl_handle, array(
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_HEADER => false
			));

// Executing curl request and storing response
$output = curl_exec($curl_handle);

//Checking for errors
if ($output === FALSE) {
	echo "cURL Error: " . curl_error($curl_handle);
}
// (Optional) Close cURL Session - free up handle
curl_close($curl_handle);

Working with PHP cURL

Initializing cURL - curl_init()

Initializes cURL session and returns a handle for accessing the session.

<?php

/* SYNTAX DESCRIPTION
resource curl_init ([ string $url = NULL ] )
*/

//Example
$curl_handle = curl_init();

//OR setting the cURL session URL on init
$curl_handle = curl_init("http://php.net/");

If $url is provided it's value is set as the cURL session's CURLOPT_URL as would have been defined by the curl_setopt function (see below). It Returns a cURL resource handle on success or FALSE on errors.

Setting cURL Options - curl_setopt

Syntax description for setting options

<?php

/* SYNTAX DESCRIPTION
//using curl_setopt
bool curl_setopt ( resource $curl_handle , int $option , mixed $value )

//OR Using curl_setop_array
bool curl_setopt_array ( resource $curl_handle , array $options )
*/

// EXAMPLES 

//Example 1, Setting curl_setopt options for downloading file via FTP
curl_setopt($curl_handle, CURLOPT_URL, 'ftp://ftp.ftpaddress.com/filelocation/file.txt');
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl_handle, CURLOPT_USERPWD, 'username:password');

//Example 2, Using curl_setopt_array
curl_setopt_array($curl_handle, array(
			CURLOPT_URL => 'ftp://ftp.ftpaddress.com/filelocation/file.txt',
			CURLOPT_RETURNTRANSFER => TRUE,
			CURLOPT_USERPWD => 'username:password'
			));
Commonly used PHP/cURL Options

For all curl_setopt/curl_setopt_array options, kindly visit PHP's curl_setopt documentation page (here). The list below shows the option name and the value and use. e.g If CURLOPT_AUTOREFERER is set to TRUE cURL will follow a Location: redirect.

The options listed below require boolean values.The default values are FALSE unless explicitly stated:

  • CURLOPT_AUTOREFERER - If TRUE cURL will follow a Location: redirect
  • CURLOPT_COOKIESESSION - If TRUE forces a new cookie session
  • CURLOPT_CONNECT_ONLY - (PHP > 5.5) If TRUE performs connection but no data is transferred
  • CURLOPT_FAILONERROR - If TRUE fail verbosely if the HTTP code returned is greater than or equal to 400
  • CURLOPT_CRLF - If TRUE convert Unix newlines to CRLF newlines on transfers
  • CURLOPT_FILETIME - If TRUE attempt to retrieve the modification date of the remote document
  • CURLOPT_FRESH_CONNECT - If TRUE force the use of a new connection instead of a cached one
  • CURLOPT_HEADER - If TRUE include the header in the output
  • CURLOPT_NOBODY - If TRUE exclude the body from the output. Sets request method to HEAD
  • CURLOPT_POST - If TRUE do a regular HTTP POST (eg as used by forms)
  • CURLOPT_RETURNTRANSFER - If TRUE return the transfer as a string, if FALSE, return TRUE or FALSE on success
  • CURLOPT_SSL_VERIFYPEER - If TRUE [default value] cURL must verify the peer's certificate
  • CURLOPT_VERBOSE - If TRUE output verbose information

This list includes options that require integer values

  • CURLOPT_CONNECTTIMEOUT - number of seconds to wait while trying to connect. Use 0 to wait indefinitely. (To use microseconds, if on PHP > 5.2.3 use CURLOPT_CONNECTTIMEOUTMS )
  • CURLOPT_RESUME_FROM - offset, in bytes, to resume a transfer from
  • CURLOPT_TIMEOUT - maximum number of seconds to allow cURL functions to execute (on PHP > 5.2.3 CURLOPT_TIMEOUT_MS)

This list includes options that require string values

  • CURLOPT_URL - URL to fetch. This can also be set when initializing a session with curl_init()
  • CURLOPT_USERAGENT - contents of the User-Agent: header to be used in a HTTP request
  • CURLOPT_REFERER - contents of the Referer: header to be used in a HTTP request
  • CURLOPT_POSTFIELDS - full data to post in a HTTP "POST" operation
  • CURLOPT_USERPWD - username and password formatted as [username]:[password]" to use for the connection
  • CURLOPT_CUSTOMREQUEST - custom request method to use instead of "GET" or "HEAD" when doing a HTTP request
  • CURLOPT_PROXY - HTTP proxy to tunnel requests through
  • CURLOPT_PROXYUSERPWD - username and password formatted as [username]:[password]" for proxy

This list includes options that require array values

  • CURLOPT_HTTPHEADER - array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')

Executing cURL session - curl_exec

Executes given cURL session. The cURL session should already be initialized and have set options.

RETURNS TRUE on success and FALSE
NOTE: if CURLOPT_RETURNTRANSFER is set (whether TRUE or FALSE) in the session options, curl_exec will return raw content fetched on success.

<?php

/* SYNTAX DESCRIPTION
mixed curl_exec ( resource $curl_handle )
*/

//Example
$result  = curl_exec($curl_handle);

Handling Errors

Testing for errors can be done through the cURL session, but usually done curl_exec

<?php

//Basic Error Checking
$result = curl_exec($curl_handle);
if ( $result === FALSE){
	echo 'cURL Error: ' . curl_error($curl_handle); //echoes last session error
}

//If you want to check out information regarding the session
var_dump(curl_getinfo($curl_handle));

Closing cURL Session curl_close

Closing cURL session - Frees up all session resources; the cURL handle is also deleted

<?php

/* SYNTAX DESCRIPTION
void curl_close ( resource $curl_handle )
*/

//usage
curl_close($curl_handle);

Other Useful PHP cURL Functions:

While you may not require them in your workflow, here's a set of other useful PHP cURL functions that may not have featured in the examples above:

  • curl_copy_handle - Copy cURL (handle along with its options)
  • curl_strerror - Return string describing the given error code
  • curl_pause - Pause and unpause a connection
  • curl_reset - Reset all options of a libcurl session handle
  • curl_share_init - Initialize a cURL share handle
  • curl_multi_init - Returns a new cURL multi handle
  • curl_version - Gets cURL version information

PHP cURL Tips, Tricks and Common Mistakes

Here are several tips to make help you use cURL better:

  • Remember to url_encode() URLs before using as curl_init() parameter or setting as CURLOPT_URL

Common cURL Errors and Mistakes

SSL Verification error when accessing secure URL, esp from localhost

SSL certificate problem: unable to get local issuer certificate

Cause: In cURL > 7.10, SSL verification is enabled by default, the error may arise if your system does not have up to date Certificate Authorities or the remote server certificate is not properly set up.

Solution:

  • For PHP > 5.3.7
    Download a list file with an up-to-date certificate authorities (this page), and upload it to your server and add absolute location to your php.ini:
    curl.cainfo=<path-to>cacert.pem
    Restart your web server, and it'll work!
  • OR (NOT recommended) - Do not use unless absolutely necessary as it opens up your system to a man-in-the-middle attack
    Set the curl_setopt option CURLOPT_SSL_VERIFYPEER to FALSE

Other Common Solutions/Mistakes when working with cURL on PHP

  • Your server does not have php_curl extension installed or enabled. Use function_exists('curl_init'), to quickly check if the extension is active.
  • Remember to valid/filter all data received through cURL request before using them
Advanced PHP cURL Library Tutorial

Here's an advanced tutorial with an in-depth look at handling cURL request with PHP:

September 25, 2014