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
Working with PHP cURL
Initializing cURL - curl_init()
Initializes cURL session and returns a handle for accessing the session.
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
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: redirectCURLOPT_COOKIESESSION
- If TRUE forces a new cookie sessionCURLOPT_CONNECT_ONLY
- (PHP > 5.5) If TRUE performs connection but no data is transferredCURLOPT_FAILONERROR
- If TRUE fail verbosely if the HTTP code returned is greater than or equal to 400CURLOPT_CRLF
- If TRUE convert Unix newlines to CRLF newlines on transfersCURLOPT_FILETIME
- If TRUE attempt to retrieve the modification date of the remote documentCURLOPT_FRESH_CONNECT
- If TRUE force the use of a new connection instead of a cached oneCURLOPT_HEADER
- If TRUE include the header in the outputCURLOPT_NOBODY
- If TRUE exclude the body from the output. Sets request method to HEADCURLOPT_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 successCURLOPT_SSL_VERIFYPEER
- If TRUE [default value] cURL must verify the peer's certificateCURLOPT_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 fromCURLOPT_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 withcurl_init()
CURLOPT_USERAGENT
- contents of the User-Agent: header to be used in a HTTP requestCURLOPT_REFERER
- contents of the Referer: header to be used in a HTTP requestCURLOPT_POSTFIELDS
- full data to post in a HTTP "POST" operationCURLOPT_USERPWD
- username and password formatted as[username]:[password]"
to use for the connectionCURLOPT_CUSTOMREQUEST
- custom request method to use instead of "GET" or "HEAD" when doing a HTTP requestCURLOPT_PROXY
- HTTP proxy to tunnel requests throughCURLOPT_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 formatarray('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.
Handling Errors
Testing for errors can be done through the cURL session, but usually done curl_exec
Closing cURL Session curl_close
Closing cURL session - Frees up all session resources; the cURL handle is also deleted
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 codecurl_pause
- Pause and unpause a connectioncurl_reset
- Reset all options of a libcurl session handlecurl_share_init
- Initialize a cURL share handlecurl_multi_init
- Returns a new cURL multi handlecurl_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 ascurl_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 thecurl_setopt
optionCURLOPT_SSL_VERIFYPEER
toFALSE
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
Tutorials with an in-depth look at work with PHP/cURL: