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 a simple PHP function:
$content = file_get_contents("http://www.aezo.cn"); // or $lines = file("http:/<span style="font-family: Simsun;">/www.aezo.cn</span><span style="font-family: Simsun;">");</span> // or readfile("http://www.aezo.cn");
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.
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. 初始化 $ch = curl_init(); // 2. 设置选项,包括URL curl_setopt($ch, CURLOPT_URL, "http://www.aezo.cn"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); // 3. 执行并获取HTML文档内容 $output = curl_exec($ch); // 4. 释放curl句柄 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 when comparing, we use "=== FALSE" instead of "== FALSE" . Because we have to distinguish between empty output and the Boolean value FALSE, which is the real error.
The above introduces the quick start of cURL based on PHP (1), including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.