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.
CURLIt 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:
Reference content is as follows: $ 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 cannot use it to complete difficult tasks, such as coockies processing, verification, form submission, and file upload.
Reference:
CURL is a powerful library that supports many different protocols and options and provides URL request-related details.
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
Reference content is as follows: // 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 the 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 ):
Reference content is as follows: //... $ 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.