At first, cURL was designed as a command line tool. Fortunately, php also supports cURL. Through cURL, we can freely send HTTP requests to a url in the php program to obtain or submit data, and support other protocols, such as FTP and Telnet.
I. Advantages of curl
You may say that you can easily obtain the content of a url in php. you only need to use the file_get_contents, file, or readfile functions to achieve this easily without using cURL:
The code is as follows:
$ Content = file_get_contents ("http://www.360weboy.com ");
$ Lines = file ("http://www.360weboy.com ");
Readfile ("http://www.360weboy.com ");
Yes, the above functions are very convenient to use in some cases, but I feel that these functions are not flexible enough to handle errors. In addition, if you want to submit form data, upload files, process cookies or perform authentication tasks to a server in a php program, the above three functions are not competent at all. At this time, cURL will reflect its value.
CURl not only supports many network protocols, but also provides specific url request information, which is very powerful!
II. steps for curl
To use cURL to send a url request, perform the following steps:
1. initialization
2. set Request options
3. execute a cURL session and obtain related Replies
4. release the cURL handle and close a cURL session.
The code is as follows:
// 1. initialize a cURL session
$ Ch = curl_init ();
// 2. set Request options, including specific URLs
Curl_setopt ($ ch, CURLOPT_URL, "http://www.360weboy.com ");
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_HEADER, 0 );
// 3. execute a cURL session and obtain related Replies
$ Response = curl_exec ($ ch );
// 4. release the cURL handle and close a cURL session
Curl_close ($ ch );
The reason why cURL is powerful is embodied in step 2. You can use curl_setopt to flexibly set Request options, there are a lot of options, specific can refer to the http://cn2.php.net/manual/zh/function.curl-setopt.php
III. Error handling
In the above code, you can also add the code for error handling:
The code is as follows:
$ Response = curl_exec ($ ch );
If ($ response = FALSE ){
Echo "cURL specific error information:". curl_error ($ ch );
}
Note that you must use ===when making the above judgment, because the request response may be a null string, and curl returns FALSE in case of a request error, therefore, we must use = instead of =.
4. obtain the specific information of the curl request
After executing a cURL request, you can use curl_getinfo to obtain the specific information of the request:
The code is as follows:
Curl_exec ($ ch );
$ Curl_info = curl_getinfo ($ ch );
Echo "the http response code received is: {$ curl_info ['http _ Code']}";
The above $ curl_info is an associated array from which you can obtain a lot of specific request information. Reference http://cn2.php.net/manual/zh/function.curl-getinfo.php
5. use curl to send a post request
As we mentioned earlier, when sending a get request to a url, there is no need to use cURL to send a get request. you can use the convenient file_get_contents function to complete the request. However, when submitting a form, data is submitted through the content area of the post request, rather than passing through url parameters. in this case, we should use flexible cURL to simulate post requests.
Now, let's use cURL to simulate sending a post request to the post. php script, submit a few pieces of data to post. php, and then output the data in the post request in post. php. The sample code is as follows:
The code is as follows:
$ Url = "http://www.360weboy.me/post.php ";
$ Post_data = array (
"Blog_name" => "360 weboy ",
"Blog_url" => "http://www.360weboy.com ",
"Action" => "Submit"
);
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
// Set the request type to post
Curl_setopt ($ ch, CURLOPT_POST, 1 );
// Add post data to the request
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post_data );
// Execute the post request to get a response
$ Response = curl_exec ($ ch );
Curl_close ($ ch );
Echo $ response;
After the above request is sent to post. php and output through print_r ($ _ POST), the sample code above will output the following response:
The code is as follows:
Array
(
[Blog_name] = & gt; 360 weboy
[Blog_url] => http://www.360weboy.com
[Action] => Submit
)
As we can see, cURL successfully sends a post request to post. php, submits some data, receives a response from post. php, and finally outputs a response. Although the above example is simple, it fully demonstrates the convenience and strength of cURL to send post requests. you can write a post on curl_setopt.
VI. file Upload
Next let's take a look at how to upload a file by sending a post request via cURL. This example shows how to upload files in PHP file uploads. in php file uploads, files are uploaded through form submission, so how can we implement it through cURL?
The code is as follows:
$ Url = "http://www.360weboy.me/upload.php ";
$ Post_data = array (
"Attachment" => "@ E:/jackblog/boy.jpg"
);
// Initialize the cURL session
$ Ch = curl_init ();
// Set the request url
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
// Set it to the post request type
Curl_setopt ($ ch, CURLOPT_POST, 1 );
// Set the specific post data
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post_data );
$ Response = curl_exec ($ ch );
Curl_close ($ ch );
Print_r ($ response );
With the above example code, you can upload Boy.jpg on my local machine to the local server's upload. php. if you output the upload information in upload. php, the final output of the above sample code will be:
The code is as follows:
Array
(
[Attachment] => Array
(
[Name] => boy.jpg
[Type] => application/octet-stream
[Tmp_name] => D: \ xampp \ tmp \ phpF27D. tmp
[Error] => 0
[Size] = & gt; 11490
)
)
It can be seen that if you want to upload a file through cURL, you only need to set the path of the uploaded file as the post data to the curl request, and add @ in front of the path.
VII. file download
After uploading files, you can also use curl to automatically download and save the files. One thing to add is that when you execute a curl request, if you need to obtain the returned content instead of directly outputting the returned content, do not forget to use the following code settings, because curl outputs the reply content of the request by default:
The code is as follows:
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Assume that there is a test.zip file under the weboyserver root directory. we need to download it and save it to a local file. then we can try the following code:
The code is as follows:
// Set the url of the requested download object
$ Url = 'http: // www.360weboy.com/test.zip ';
// Path of the local file
$ Path = 'local/path/to/test.zip ';
// Initialize the request, set the request, obtain the reply, and close the session
$ Ch = curl_init ($ url );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true );
$ Data = curl_exec ($ ch );
Curl_close ($ ch );
// Write the file content to a local file
File_put_contents ($ path, $ data );
Note: I have omitted the error handling code above, just as an example. In practice, you still need to use the curl_getinfo function to handle the error!
The above code is not applicable to downloading large files, because you need to first read the file into the memory, and then write it into the local hard disk after all the content is read. Even if the memory limit set in php is very large, this situation has a great impact on performance. Therefore, we should allow curl to take over this task for downloading large files and writing them. in this case, there is no problem. See the following code:
The code is as follows:
$ Url = 'http: // www.360weboy.com/test.zip ';
$ Path = 'local/path/to/test.zip ';
// Open a local file
$ Fp = fopen ($ path, 'w ');
// Tell curl local file handle
$ Ch = curl_init ($ url );
Curl_setopt ($ ch, CURLOPT_FILE, $ fp );
Curl_exec ($ ch );
Curl_close ($ ch );
Fclose ($ fp );
In the above code, we first open a local file, set the file handle to curl, and then let curl read remote data while writing data to the local file. Because we do not need to obtain remote reply content in the program, we only need to execute the request.
8. http verification
If the server needs to verify the request, you can use the following sample code:
The code is as follows:
$ Url = "http://www.360weboy.com/users ";
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, $ url );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
// Set the user name and password
Curl_setopt ($ ch, CURLOPT_USERPWD, "username: password ");
// Set redirection
Curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, 1 );
Curl_setopt ($ ch, CURLOPT_UNRESTRICTED_AUTH, 1 );
$ Response = curl_exec ($ ch );
Curl_close ($ ch );
9. send a request through a proxy
CURL can also send requests to the proxy server. please take a look at the sample code:
The code is as follows:
$ Ch = curl_init ();
Curl_setopt ($ ch, CURLOPT_URL, 'http: // www.360weboy.com ');
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
// Set the proxy IP address
Curl_setopt ($ ch, CURLOPT_PROXY, '192. 73.173.50: 100 ');
// Set the user name and password for verification.
Curl_setopt ($ ch, CURLOPT_PROXYUSERPWD, 'username: password ');
$ Response = curl_exec ($ ch );
Curl_close ($ ch );
10. send json data
Finally, let's take a look at using cURL to send json data to the server. The specific code is as follows:
The code is as follows:
$ Url = 'http: // www.360weboy. me/json. php ';
// Create a json string
$ Data = array ('site' => '360weboys', 'URL' => 'http: // www.360weboy.com ', 'Email' => '360weboy @ gmail.com ');
$ Json_string = json_encode ($ data );
$ Ch = curl_init ($ url );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
// Send the preceding json string through the post request
Curl_setopt ($ ch, CURLOPT_CUSTOMREQUEST, "POST ");
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, array ('data' => $ json_string ));
$ Response = curl_exec ($ ch );
Curl_close ($ ch );
Echo $ response;
As you can see, the above request is sent to the json of my local server. in php, I use json_decode in this file to convert the received json string to an object, and then output the email field. the code is as follows:
The code is as follows:
$ Json_data = json_decode ($ _ POST ['data']);
Echo $ json_data-> email;
The json string accepted in the above code is:
The code is as follows:
'{"Site": "360 weboy", "url": "http: \/www.360weboy.com", "email": "360weboy@gmail.com "}'
After json_decode, it is converted to the data format in php, become an object, so you can access the value of the e-mail field through $ json_data-> email, and finally the output 360weboy@gmail.com. You can use the above code to test.
If the following php array is used to generate a json string:
The code is as follows:
$ Data = array ('360weboys', 'http: // www.360weboy.com ', '360weboy @ gmail.com ');
The generated json string is as follows:
The code is as follows:
'["360 weboy", "http: \ // www.360weboy.com", "360weboy@gmail.com"]'
After json_decode processing, the above json string will be converted to the array format in php. if you want to get an email, you can access it through $ json_data [2.
11. Summary
In this blog post, we only list some cURL functions. the sample code is relatively simple. However, I believe you will be tempted to use cURL after reading it! Find the relevant information and test the manual!
Now, write it here! Thank you for your patience!