In this post, I’m going back to basics to talk about accessing remote URLs with cURL.
In PHP, there are actually four ways to access a remote URL –
fsockopen(), cURL extensions and
HTTP_Request class from the PEAR library. Now, choosing one way over another really depends on your needs for simplicity, control, and portability.
Generally, I prefer using cURL simply because it’s easy to understand and it’s really powerful. cURL supports a number of different protocols and gives your access to the response headers. It even has the capability to do parallel access if you call the ‘curl_multi’ group of functions (I’ll save this for another post one day).
To use cURL, you need to make sure that your PHP install has the library enabled. Read this posting on how to enable cURL for your PHP.
Fetching a URL with the GET Method
The simplest way to start using cURL is to fetch a URL with the GET method.
So what is going on? The simple example above really maps out 4 stages of using cURL. You start by calling the
curl_init() to get a handle on the URL you wan to access. Then, you set some options using
curl_setopt().After that, you execute what you want to do with
curl_exec(). Lastly, you close the handle using
The control of the curl functions is all to do with what options you set using
curl_setopt(). PHP lists out all the options available at
curl_setopt() page. Frankly, this is probably the hardest part about using the cURL library – understanding what all these options do. It was pretty daunting when I first started using.
Following on, here are some of the more commonly used (at least by me anyway) options for cURL.
Fetching a protected URL with the GET Method
To do this, you need to set the CURLOPT_USERPWD option, like so:
Submitting data to a URL with the POST Method
In this case, you need to set the CURLOPT_POST and CURLOPT_POSTFIELDS option.
The parameters you want to pass should be formatted like a querystring. If you are expecting some response after posting, then you need to enable the CURLOPT_RETURNTRANSFER option.
Fetching a URL with Custom Headers
You can also retrieve URLs that requires specific headers to be sent with the request. You can do so with CURLOPT_HTTPHEADER option.
cURL has special options for setting the Referer and User-Agent request headers —
CURLOPT_REFERER and CURLOPT_USERAGENT:
I’m going to stop here. If you’re new to cURL, hopefully this has been a good broad tutorial to get you started. In the Web 2.0 age, online services constantly pop-up to allow you to programmatically connect to them, cURL is the best tool you can have to help you access those services.