I used curl extension to write a php interface and found that it was not installed. Khan introduced the installation method in linux because of the linux system I used.
I used curl extension to write a php interface and found that it was not installed. Khan
Because of the linux system I use, I will introduce the installation method in linux.
Enter
Apt-cache search curl | grep php
Query supported php names of curl
The following content may be returned:
Php5-curl-CURL module for php5
Installation:
Sudo apt-get install php5-curl
Restart apache
Sudo/etc/init. d/apache2 restart
Usage:
CURL is a tool that uses URL syntax to transmit files and data. it supports many protocols, such as HTTP, FTP, and TELNET.
Why do we use cURL?
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:
1 2 3 4 5
|
$ Content = file_get_contents ("http://www.blogwl.com "); // Or $ Lines = file ("http://www.blogwl.com "); // Or Readfile (http://www.blogwl.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.
Basic structure
Before learning more complex functions, let's take a look at the basic steps for creating cURL requests in PHP:
1. initialization
2. set variables
3. execute and obtain results
4. release the cURL handle
1 2 3 4 5 6 7 8 9 10
|
// 1. initialization $ Ch = curl_init (); // 2. set options, including URL Curl_setopt ($ ch, CURLOPT_URL, "http://www.blogwl.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 ):
1 2 3 4
|
$ 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.
Obtain information
This is another optional setting item, which can obtain the relevant information of this request after the cURL is executed:
1 2 3
|
Curl_exec ($ ch ); $ Info = curl_getinfo ($ ch ); Echo 'get '. $ info ['URL'].' time consumed '. $ info ['total _ time']. 'second '; |
The returned array contains the following information:
- "Url" // resource network address
- "Content_type" // content encoding
- "Http_code" // HTTP status code
- "Header_size" // header size
- "Request_size" // request size
- "Filetime" // file creation time
- "Ssl_verify_result" // SSL verification result
- "Redirect_count" // jump Technology
- "Total_time" // total time consumed
- "Namelookup_time" // DNS query time
- "Connect_time" // waiting for connection time
- "Pretransfer_time" // pre-transmission preparation time
- "Size_upload" // size of the uploaded data
- "Size_download" // size of the downloaded data
- "Speed_download" // download speed
- "Speed_upload" // upload speed
- "Download_content_length" // The length of the downloaded content
- "Upload_content_length" // length of the uploaded content
- "Starttransfer_time" // start time of transmission
- "Redirect_time" // time consumed by redirection
Use the POST method to send data
When a GET request is initiated, data can be transmitted to a URL through the query string. For example, when searching in google, the search key is part of the query string of the URL:
Http://www.google.com/search? Q = nettuts
In this case, you may not need cURL to simulate it. You can get the same result by throwing this URL to "file_get_contents.
However, some HTML forms are submitted using the POST method. When such a form is submitted, the data is sent through the HTTP request body instead of the query string. For example, when using the CodeIgniter Forum form, no matter what keyword you enter, it is always POST to the following page:
Http://codeigniter.com/forums/do_search/
You can use PHP scripts to simulate such URL requests. First, create a new file that accepts and displays POST data. we name it post_output.php:
Print_r ($ _ POST );
Next, write a PHP script to execute the cURL request:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
$ Url = "http: // localhost/post_output.php "; $ Post_data = array ( "Foo" => "bar ", "Query" => "Nettuts ", "Action" => "Submit" ); $ Ch = curl_init (); Curl_setopt ($ ch, CURLOPT_URL, $ url ); Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 ); // We are posting data! Curl_setopt ($ ch, CURLOPT_POST, 1 ); // Add the post variable Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post_data ); $ Output = curl_exec ($ ch ); Curl_close ($ ch ); Echo $ output; |
Result:
1 2 3 4 5 6 7
|
Array (
[Foo] => bar [Query] => Nettuts [Action] => Submit
) |
This script sends a POST request to post_output.php. The $ _ POST variable on this page is returned. we captured this output using cURL.
File Upload
The uploaded file is very similar to the previous POST. Because all file upload forms are submitted through the POST method.
First, create a page for receiving files, named upload_output.php:
Print_r ($ _ FILES );
The following is a script for executing a file Upload task:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
$ Url = "http: // localhost/upload_output.php "; $ Post_data = array ( "Foo" => "bar ", // Address of the local file to be uploaded "Upload" => "@ C:/wamp/www/test.zip" ); $ Ch = curl_init (); Curl_setopt ($ ch, CURLOPT_URL, $ url ); Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 ); Curl_setopt ($ ch, CURLOPT_POST, 1 ); Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post_data ); $ Output = curl_exec ($ ch ); Curl_close ($ ch ); Echo $ output; |
If you need to upload a file, you only need to pass the file path like a post variable, but remember to add the @ symbol before it. Execute this script and you will get the following output:
1 2 3 4 5 6 7 8 9
|
Array ( [Upload] => Array ( [Name] => test.zip [Type] => application/octet-stream [Tmp_name] => C: \ wamp \ tmp \ php4CCB. tmp [Error] => 0 [Size] = & gt; 11122 ) ) |
CURL batch processing (multi cURL)
CURL also has an advanced feature, handle ). This feature allows you to open multiple URL connections simultaneously or asynchronously.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
// Create two cURL resources $ Response = curl_init (); $ Ch2 = curl_init (); // Specify the URL and appropriate parameters Curl_setopt ($ scheme, CURLOPT_URL, "http://lxr.php.net /"); Curl_setopt ($ scheme, CURLOPT_HEADER, 0 ); Curl_setopt ($ ch2, CURLOPT_URL, "http://www.php.net /"); Curl_setopt ($ ch2, CURLOPT_HEADER, 0 ); // Create a cURL batch handle $ Mh = curl_multi_init (); // Add the first two resource handles Curl_multi_add_handle ($ mh, $ handle ); Curl_multi_add_handle ($ mh, $ ch2 ); // Predefine a state variable $ Active = null; // Execute batch processing Do { $ Mrc = curl_multi_exec ($ mh, $ active ); } While ($ mrc = CURLM_CALL_MULTI_PERFORM ); While ($ active & $ mrc = CURLM_ OK ){ If (curl_multi_select ($ mh )! =-1 ){ Do { $ Mrc = curl_multi_exec ($ mh, $ active ); } While ($ mrc = CURLM_CALL_MULTI_PERFORM ); } } // Close each handle Curl_multi_remove_handle ($ mh, $ handle ); Curl_multi_remove_handle ($ mh, $ ch2 ); Curl_multi_close ($ mh ); |
Here, you need to open multiple cURL handles and assign them to a batch processing handle. Then you just need to wait for it to be executed in a while loop.
There are two main loops in this example. The first do-while loop repeatedly calls curl_multi_exec (). This function is non-blocking, but will be executed as little as possible. It returns a status value. as long as the value is equal to the constant CURLM_CALL_MULTI_PERFORM, it indicates that there is still some urgent work to be done (for example, sending the http header information of the corresponding URL ). That is to say, we need to call this function continuously until the return value changes.
The next while loop continues only when the $ active variable is true. This variable was previously passed to curl_multi_exec () as the second parameter, which indicates that as long as there is any active connection in the batch handle. Next, we call curl_multi_select (), which is "blocked" before an active connection (for example, server response reception) occurs. After this function is successfully executed, we will go to another do-while loop and continue the next URL.