Advertisement
  1. Code
  2. PHP

Techniques for Mastering cURL

Scroll to top

cURL is a tool for transferring files and data with URL syntax, supporting many protocols including HTTP, FTP, TELNET and more. Initially, cURL was designed to be a command line tool. Lucky for us, the cURL library is also supported by PHP. In this article, we will look at some of the advanced features of cURL, and how we can use them in our PHP scripts.

Why cURL?

It's true that there are other ways of fetching the contents of a web page. Many times, mostly due to laziness, I have just used simple PHP functions instead of cURL:

1
2
$content = file_get_contents("http://www.nettuts.com");
3
4
// or

5
6
$lines = file("http://www.nettuts.com");
7
8
// or

9
10
readfile("http://www.nettuts.com");

However they have virtually no flexibility and lack sufficient error handling. Also, there are certain tasks that you simply can not do, like dealing with cookies, authentication, form posts, file uploads etc.

cURL is a powerful library that supports many different protocols, options, and provides detailed information about the URL requests.

Basic Structure

Before we move on to more complicated examples, let's review the basic structure of a cURL request in PHP. There are four main steps:

  1. Initialize
  2. Set Options
  3. Execute and Fetch Result
  4. Free up the cURL handle
1
2
// 1. initialize

3
$ch = curl_init();
4
5
// 2. set the options, including the url

6
curl_setopt($ch, CURLOPT_URL, "http://www.nettuts.com");
7
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
8
curl_setopt($ch, CURLOPT_HEADER, 0);
9
10
// 3. execute and fetch the resulting HTML output

11
$output = curl_exec($ch);
12
13
// 4. free up the curl handle

14
curl_close($ch);

Step #2 (i.e. curl_setopt() calls) is going to be a big part of this article, because that is where all the magic happens. There is a long list of cURL options that can be set, which can configure the URL request in detail. It might be difficult to go through the whole list and digest it all at once. So today, we are just going to use some of the more common and useful options in various code examples.

Checking for Errors

Optionally, you can also add error checking:

1
2
// ...

3
4
$output = curl_exec($ch);
5
6
if ($output === FALSE) {
7
8
	echo "cURL Error: " . curl_error($ch);
9
10
}
11
12
// ...

Please note that we need to use "=== FALSE" for comparison instead of "== FALSE". Because we need to distinguish between empty output vs. the boolean value FALSE, which indicates an error.

Getting Information

Another optional step is to get information about the cURL request, after it has been executed.

1
2
// ...

3
4
curl_exec($ch);
5
6
$info = curl_getinfo($ch);
7
8
echo 'Took ' . $info['total_time'] . ' seconds for url ' . $info['url'];
9
10
// ...

Following information is included in the returned array:

  • "url"
  • "content_type"
  • "http_code"
  • "header_size"
  • "request_size"
  • "filetime"
  • "ssl_verify_result"
  • "redirect_count"
  • "total_time"
  • "namelookup_time"
  • "connect_time"
  • "pretransfer_time"
  • "size_upload"
  • "size_download"
  • "speed_download"
  • "speed_upload"
  • "download_content_length"
  • "upload_content_length"
  • "starttransfer_time"
  • "redirect_time"

Detect Redirection Based on Browser

In this first example, we will write a script that can detect URL redirections based on different browser settings. For example, some websites redirect cellphone browsers, or even surfers from different countries.

We are going to be using the CURLOPT_HTTPHEADER option to set our outgoing HTTP Headers including the user agent string and the accepted languages. Finally we will check to see if these websites are trying to redirect us to different URLs.

1
2
// test URLs

3
$urls = array(
4
	"http://www.cnn.com",
5
	"http://www.mozilla.com",
6
	"http://www.facebook.com"
7
);
8
// test browsers

9
$browsers = array(
10
11
	"standard" => array (
12
		"user_agent" => "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 (.NET CLR 3.5.30729)",
13
		"language" => "en-us,en;q=0.5"
14
		),
15
16
	"iphone" => array (
17
		"user_agent" => "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A537a Safari/419.3",
18
		"language" => "en"
19
		),
20
21
	"french" => array (
22
		"user_agent" => "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB6; .NET CLR 2.0.50727)",
23
		"language" => "fr,fr-FR;q=0.5"
24
		)
25
26
);
27
28
foreach ($urls as $url) {
29
30
	echo "URL: $url\n";
31
32
	foreach ($browsers as $test_name => $browser) {
33
34
		$ch = curl_init();
35
36
		// set url

37
		curl_setopt($ch, CURLOPT_URL, $url);
38
39
		// set browser specific headers

40
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
41
				"User-Agent: {$browser['user_agent']}",
42
				"Accept-Language: {$browser['language']}"
43
			));
44
45
		// we don't want the page contents

46
		curl_setopt($ch, CURLOPT_NOBODY, 1);
47
48
		// we need the HTTP Header returned

49
		curl_setopt($ch, CURLOPT_HEADER, 1);
50
51
		// return the results instead of outputting it

52
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
53
54
		$output = curl_exec($ch);
55
56
		curl_close($ch);
57
58
		// was there a redirection HTTP header?

59
		if (preg_match("!Location: (.*)!", $output, $matches)) {
60
61
			echo "$test_name: redirects to $matches[1]\n";
62
63
		} else {
64
65
			echo "$test_name: no redirection\n";
66
67
		}
68
69
	}
70
	echo "\n\n";
71
}

First we have a set of URLs to test, followed by a set of browser settings to test each of these URLs against. Then we loop through these test cases and make a cURL request for each.

Because of the way setup the cURL options, the returned output will only contain the HTTP headers (saved in $output). With a simple regex, we can see if there was a "Location:" header included.

When you run this script, you should get an output like this:

POSTing to a URL

On a GET request, data can be sent to a URL via the "query string". For example, when you do a search on Google, the search term is located in the query string part of the URL:

1
http://www.google.com/search?q=nettuts

You may not need cURL to simulate this in a web script. You can just be lazy and hit that url with "file_get_contents()" to receive the results.

But some HTML forms are set to the POST method. When these forms are submitted through the browser, the data is sent via the HTTP Request body, rather than the query string. For example, if you do a search on the CodeIgniter forums, you will be POSTing your search query to:

1
http://codeigniter.com/forums/do_search/

We can write a PHP script to simulate this kind of URL request. First let's create a simple file for accepting and displaying the POST data. Let's call it post_output.php:

1
2
print_r($_POST);

Next we create a PHP script to perform a cURL request:

1
2
$url = "http://localhost/post_output.php";
3
4
$post_data = array (
5
	"foo" => "bar",
6
	"query" => "Nettuts",
7
	"action" => "Submit"
8
);
9
10
$ch = curl_init();
11
12
curl_setopt($ch, CURLOPT_URL, $url);
13
14
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
15
// we are doing a POST request

16
curl_setopt($ch, CURLOPT_POST, 1);
17
// adding the post variables to the request

18
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
19
20
$output = curl_exec($ch);
21
22
curl_close($ch);
23
24
echo $output;

When you run this script, you should get an output like this:

It sent a POST to the post_output.php script, which dumped the $_POST variable, and we captured that output via cURL.

File Upload

Uploading files works very similarly to the previous POST example, since all file upload forms have the POST method.

First let's create a file for receiving the request and call it upload_output.php:

1
2
print_r($_FILES);

And here is the actual script performing the file upload:

1
2
$url = "http://localhost/upload_output.php";
3
4
$post_data = array (
5
	"foo" => "bar",
6
	// file to be uploaded

7
	"upload" => "@C:/wamp/www/test.zip"
8
);
9
10
$ch = curl_init();
11
12
curl_setopt($ch, CURLOPT_URL, $url);
13
14
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
15
16
curl_setopt($ch, CURLOPT_POST, 1);
17
18
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
19
20
$output = curl_exec($ch);
21
22
curl_close($ch);
23
24
echo $output;

When you want to upload a file, all you have to do is pass its file path just like a post variable, and put the @ symbol in front of it. Now when you run this script you should get an output like this:

Multi cURL

One of the more advanced features of cURL is the ability to create a "multi" cURL handle. This allows you to open connections to multiple URLs simultaneously and asynchronously.

On a regular cURL request, the script execution stops and waits for the URL request to finish before it can continue. If you intend to hit multiple URLs, this can take a long time, as you can only request one URL at a time. We can overcome this limitation by using the multi handle.

Let's look at this sample code from php.net:

1
2
// create both cURL resources

3
$ch1 = curl_init();
4
$ch2 = curl_init();
5
6
// set URL and other appropriate options

7
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
8
curl_setopt($ch1, CURLOPT_HEADER, 0);
9
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
10
curl_setopt($ch2, CURLOPT_HEADER, 0);
11
12
//create the multiple cURL handle

13
$mh = curl_multi_init();
14
15
//add the two handles

16
curl_multi_add_handle($mh,$ch1);
17
curl_multi_add_handle($mh,$ch2);
18
19
$active = null;
20
//execute the handles

21
do {
22
    $mrc = curl_multi_exec($mh, $active);
23
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
24
25
while ($active && $mrc == CURLM_OK) {
26
    if (curl_multi_select($mh) != -1) {
27
        do {
28
            $mrc = curl_multi_exec($mh, $active);
29
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
30
    }
31
}
32
33
//close the handles

34
curl_multi_remove_handle($mh, $ch1);
35
curl_multi_remove_handle($mh, $ch2);
36
curl_multi_close($mh);

The idea is that you can open multiple cURL handles and assign them to a single multi handle. Then you can wait for them to finish executing while in a loop.

There are two main loops in this example. The first do-while loop repeatedly calls curl_multi_exec(). This function is non-blocking. It executes as little as possible and returns a status value. As long as the returned value is the constant 'CURLM_CALL_MULTI_PERFORM', it means that there is still more immediate work to do (for example, sending http headers to the URLs.) That's why we keep calling it until the return value is something else.

In the following while loop, we continue as long as the $active variable is 'true'. This was passed as the second argument to the curl_multi_exec() call. It is set to 'true' as long as there are active connections withing the multi handle. Next thing we do is to call curl_multi_select(). This function is 'blocking' until there is any connection activity, such as receiving a response. When that happens, we go into yet another do-while loop to continue executing.

Let's see if we can create a working example ourselves, that has a practical purpose.

Wordpress Link Checker

Imagine a blog with many posts containing links to external websites. Some of these links might end up dead after a while for various reasons. Maybe the page is longer there, or the entire website is gone.

We are going to be building a script that analyzes all the links and finds non-loading websites and 404 pages and returns a report to us.

Note that this is not going to be an actual Wordpress plug-in. It is only a standalone utility script, and it is just for demonstration purposes.

So let's get started. First we need to fetch the links from the database:

1
2
// CONFIG

3
$db_host = 'localhost';
4
$db_user = 'root';
5
$db_pass = '';
6
$db_name = 'wordpress';
7
$excluded_domains = array(
8
	'localhost', 'www.mydomain.com');
9
$max_connections = 10;
10
// initialize some variables

11
$url_list = array();
12
$working_urls = array();
13
$dead_urls = array();
14
$not_found_urls = array();
15
$active = null;
16
17
// connect to MySQL

18
if (!mysql_connect($db_host, $db_user, $db_pass)) {
19
	die('Could not connect: ' . mysql_error());
20
}
21
if (!mysql_select_db($db_name)) {
22
	die('Could not select db: ' . mysql_error());
23
}
24
25
26
// get all published posts that have links

27
$q = "SELECT post_content FROM wp_posts

28
	WHERE post_content LIKE '%href=%'

29
	AND post_status = 'publish'

30
	AND post_type = 'post'";
31
$r = mysql_query($q) or die(mysql_error());
32
while ($d = mysql_fetch_assoc($r)) {
33
34
	// get all links via regex

35
	if (preg_match_all("!href=\"(.*?)\"!", $d['post_content'], $matches)) {
36
37
		foreach ($matches[1] as $url) {
38
39
			// exclude some domains

40
			$tmp = parse_url($url);
41
			if (in_array($tmp['host'], $excluded_domains)) {
42
				continue;
43
			}
44
45
			// store the url

46
			$url_list []= $url;
47
		}
48
	}
49
}
50
51
// remove duplicates

52
$url_list = array_values(array_unique($url_list));
53
54
if (!$url_list) {
55
	die('No URL to check');
56
}

First we have some database configuration, followed by an array of domain names we will ignore ($excluded_domains). Also we set a number for maximum simultaneous connections we will be using later ($max_connections). Then we connect to the database, fetch posts that contain links, and collect them into an array ($url_list).

Following code might be a little complex, so I will try to explain it in small steps.

1
2
// 1. multi handle

3
$mh = curl_multi_init();
4
5
// 2. add multiple URLs to the multi handle

6
for ($i = 0; $i < $max_connections; $i++) {
7
	add_url_to_multi_handle($mh, $url_list);
8
}
9
10
// 3. initial execution

11
do {
12
	$mrc = curl_multi_exec($mh, $active);
13
} while ($mrc == CURLM_CALL_MULTI_PERFORM);
14
15
// 4. main loop

16
while ($active && $mrc == CURLM_OK) {
17
18
	// 5. there is activity

19
	if (curl_multi_select($mh) != -1) {
20
21
		// 6. do work

22
		do {
23
			$mrc = curl_multi_exec($mh, $active);
24
		} while ($mrc == CURLM_CALL_MULTI_PERFORM);
25
26
		// 7. is there info?

27
		if ($mhinfo = curl_multi_info_read($mh)) {
28
			// this means one of the requests were finished

29
30
			// 8. get the info on the curl handle

31
			$chinfo = curl_getinfo($mhinfo['handle']);
32
33
			// 9. dead link?

34
			if (!$chinfo['http_code']) {
35
				$dead_urls []= $chinfo['url'];
36
37
			// 10. 404?

38
			} else if ($chinfo['http_code'] == 404) {
39
				$not_found_urls []= $chinfo['url'];
40
41
			// 11. working

42
			} else {
43
				$working_urls []= $chinfo['url'];
44
			}
45
46
			// 12. remove the handle

47
			curl_multi_remove_handle($mh, $mhinfo['handle']);
48
			curl_close($mhinfo['handle']);
49
50
			// 13. add a new url and do work

51
			if (add_url_to_multi_handle($mh, $url_list)) {
52
53
				do {
54
					$mrc = curl_multi_exec($mh, $active);
55
				} while ($mrc == CURLM_CALL_MULTI_PERFORM);
56
			}
57
		}
58
	}
59
}
60
61
// 14. finished

62
curl_multi_close($mh);
63
64
echo "==Dead URLs==\n";
65
echo implode("\n",$dead_urls) . "\n\n";
66
67
echo "==404 URLs==\n";
68
echo implode("\n",$not_found_urls) . "\n\n";
69
70
echo "==Working URLs==\n";
71
echo implode("\n",$working_urls);
72
73
// 15. adds a url to the multi handle

74
function add_url_to_multi_handle($mh, $url_list) {
75
	static $index = 0;
76
77
	// if we have another url to get

78
	if ($url_list[$index]) {
79
80
		// new curl handle

81
		$ch = curl_init();
82
83
		// set the url

84
		curl_setopt($ch, CURLOPT_URL, $url_list[$index]);
85
		// to prevent the response from being outputted

86
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
87
		// follow redirections

88
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
89
		// do not need the body. this saves bandwidth and time

90
		curl_setopt($ch, CURLOPT_NOBODY, 1);
91
92
		// add it to the multi handle

93
		curl_multi_add_handle($mh, $ch);
94
95
96
		// increment so next url is used next time

97
		$index++;
98
99
		return true;
100
	} else {
101
102
		// we are done adding new URLs

103
		return false;
104
	}
105
}

And here is the explanation for the code above. Numbers in the list correspond to the numbers in the code comments.

  1. Created a multi handle.
  2. We will be creating the add_url_to_multi_handle() function later on. Every time it is called, it will add a url to the multi handle. Initially, we add 10 (based on $max_connections) URLs to the multi handle.
  3. We must run curl_multi_exec() for the initial work. As long as it returns CURLM_CALL_MULTI_PERFORM, there is work to do. This is mainly for creating the connections. It does not wait for the full URL response.
  4. This main loop runs as long as there is some activity in the multi handle.
  5. curl_multi_select() waits the script until an activity to happens with any of the URL quests.
  6. Again we must let cURL do some work, mainly for fetching response data.
  7. We check for info. There is an array returned if a URL request was finished.
  8. There is a cURL handle in the returned array. We use that to fetch info on the individual cURL request.
  9. If the link was dead or timed out, there will be no http code.
  10. If the link was a 404 page, the http code will be set to 404.
  11. Otherwise we assume it was a working link. (You may add additional checks for 500 error codes etc...)
  12. We remove the cURL handle from the multi handle since it is no longer needed, and close it.
  13. We can now add another url to the multi handle, and again do the initial work before moving on.
  14. Everything is finished. We can close the multi handle and print a report.
  15. This is the function that adds a new url to the multi handle. The static variable $index is incremented every time this function is called, so we can keep track of where we left off.

I ran the script on my blog (with some broken links added on purpose, for testing), and here is what it looked like:

It took only less than 2 seconds to go through about 40 URLs. The performance gains are significant when dealing with even larger sets of URLs. If you open ten connections at the same time, it can run up to ten times faster. Also you can just utilize the non-blocking nature of the multi curl handle to do URL requests without stalling your web script.

Some Other Useful cURL Options

HTTP Authentication

If there is HTTP based authentication on a URL, you can use this:

1
2
$url = "http://www.somesite.com/members/";
3
4
$ch = curl_init();
5
6
curl_setopt($ch, CURLOPT_URL, $url);
7
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
8
9
// send the username and password

10
curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword");
11
12
// if you allow redirections

13
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
14
// this lets cURL keep sending the username and password

15
// after being redirected

16
curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1);
17
18
$output = curl_exec($ch);
19
20
curl_close($ch);

FTP Upload

PHP does have an FTP library, but you can also use cURL:

1
2
// open a file pointer

3
$file = fopen("/path/to/file", "r");
4
5
// the url contains most of the info needed

6
$url = "ftp://username:password@mydomain.com:21/path/to/new/file";
7
8
$ch = curl_init();
9
10
curl_setopt($ch, CURLOPT_URL, $url);
11
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
12
13
// upload related options

14
curl_setopt($ch, CURLOPT_UPLOAD, 1);
15
curl_setopt($ch, CURLOPT_INFILE, $fp);
16
curl_setopt($ch, CURLOPT_INFILESIZE, filesize("/path/to/file"));
17
18
// set for ASCII mode (e.g. text files)

19
curl_setopt($ch, CURLOPT_FTPASCII, 1);
20
21
$output = curl_exec($ch);
22
curl_close($ch);

Using a Proxy

You can perform your URL request through a proxy:

1
2
$ch = curl_init();
3
4
curl_setopt($ch, CURLOPT_URL,'http://www.example.com');
5
6
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
7
8
// set the proxy address to use

9
curl_setopt($ch, CURLOPT_PROXY, '11.11.11.11:8080');
10
11
// if the proxy requires a username and password

12
curl_setopt($ch, CURLOPT_PROXYUSERPWD,'user:pass');
13
14
$output = curl_exec($ch);
15
16
curl_close ($ch);

Callback Functions

It is possible to have cURL call given callback functions during the URL request, before it is finished. For example, as the contents of the response is being downloaded, you can start using the data, without waiting for the whole download to complete.

1
2
$ch = curl_init();
3
4
curl_setopt($ch, CURLOPT_URL,'https://code.tutsplus.com');
5
6
curl_setopt($ch, CURLOPT_WRITEFUNCTION,"progress_function");
7
8
curl_exec($ch);
9
10
curl_close ($ch);
11
12
13
function progress_function($ch,$str) {
14
15
	echo $str;
16
	return strlen($str);
17
18
}

The callback function MUST return the length of the string, which is a requirement for this to work properly.

As the URL response is being fetched, every time a data packet is received, the callback function is called.

Conclusion

We have explored the power and the flexibility of the cURL library today. I hope you enjoyed and learned from the this article. Next time you need to make a URL request in your web application, consider using cURL.

Thank you and have a great day!

Write a Plus Tutorial

Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We're looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you're of the ability, please contact Jeffrey at nettuts@tutsplus.com.

Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

Write a PLUS tutorial
Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.