: This article mainly introduces the PHP-based cURL quick start (1). If you are interested in the PHP Tutorial, refer to it. CURL is a tool that uses URL syntax to transmit files and data. it supports many protocols, such as HTTP, FTP, and TELNET. The best thing is that PHP also supports the cURL Library. This article describes some advanced features of cURL and how to use it in PHP.
Why use cURL?
Yes. we can use other methods to obtain the webpage content. Most of the time, I want to be lazy and use simple PHP functions directly:
$content = file_get_contents("http://www.aezo.cn");// or$lines = file("http://www.aezo.cn");// orreadfile("http://www.aezo.cn");
However, this approach lacks flexibility and effective error handling. Moreover, you cannot use it to complete difficult tasks, such as coockies processing, verification, form submission, and file upload.
Basic structure
Before learning more complex functions, let's take a look at the basic steps for creating cURL requests in PHP:
- Initialization
- Set variables
- Execute and obtain results
- Release cURL handle
// 1. initialize $ ch = curl_init (); // 2. set options, including URLcurl_setopt ($ ch, CURLOPT_URL, "http://www.aezo.cn"); 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 mysteries are here. There is a long string of cURL parameters that can be set. they can specify the details of URL requests. It may be difficult to read and understand all at once, so today we will only try out the more common and useful options.
Check error
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);}// ...
Note that we use "= FALSE" instead of "= FALSE" for comparison ". Because we need to distinguish between null output and boolean value FALSE, the latter is a real error.
The above introduces the PHP-based cURL quick start (1), including some content, hope to be helpful to friends who are interested in PHP tutorials.