cURL is a tool that uses URL syntax to transfer files and data. It supports many protocols, such as HTTP, FTP, TELNET, etc. The best part is that PHP also supports the cURL library. This article will introduce some advanced features of cURL and how to use it in PHP.
Why use cURL?
Yes, we can obtain web content through other methods. Most of the time, because I want to be lazy, I just use simple PHP functions:
$content = file_get_contents("http://www.nettuts.com");
// or
$lines = file("http://www.nettuts.com") ;
// or
readfile(http://www.nettuts.com);
However, this approach lacks flexibility and effective error handling. Moreover, you can't use it to complete some difficult tasks - such as handling cookies, validation, form submission, file upload, etc.
Quote:
cURL is a powerful library that supports many different protocols and options and can provide various details related to URL requests.
Basic structure
Before learning more complex functions, let’s take a look at the basic steps of setting up a cURL request in PHP:
// 1. Initialization
$ch = curl_init();
// 2. Set options, including URL
curl_setopt($ch, CURLOPT_URL, "http://www. nettuts.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// 3. Execute and obtain the HTML document content
$output = curl_exec($ch);
// 4. Release curl handle
curl_close($ch);
The second step (that is, curl_setopt()) is the most important, and all the secrets are here. There is a long list of cURL parameters that can be set that specify various details of the URL request. It can be difficult to read and understand them all at once, so today we will only try the more common and useful options.
Check for errors
You can add a statement to check for errors (although this is not required):
// ...
$output = curl_exec($ch);
if ($output === FALSE) {
echo "cURL Error: " . curl_error($ch );
}
// ...
Please note that we use "=== FALSE" instead of "== FALSE" when comparing. Because we have to distinguish between empty output and the Boolean value FALSE, which is the real error.