First, Curl's advantages
You might say that it's easy to get the content of a URL in PHP, as long as it's easy to do with file_get_contents,file or ReadFile functions without using curl at all:
Copy CodeThe 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 really handy in some cases, but I feel that these functions are not flexible enough and cannot be handled incorrectly. Furthermore, if you encounter tasks such as submitting form data to a server in a PHP program, uploading files, processing cookies, or authentication, the above three functions are simply not competent. This time, curl embodies its value.
Curl not only supports a lot of network protocols, but also provides specific information about URL requests, very powerful!
Ii. simple steps to use curl
To use Curl to send URL requests, the steps are broadly divided into the following four stages:
1. Initialization
2. Set Request options
3. Perform a curl session and get related replies
4. Release the curl handle and close a curl session
Copy the Code code as follows:
1. Initializing 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. Perform a curl session and get related replies
$response = curl_exec ($ch);
4. Release the curl handle and close a curl session
Curl_close ($ch);
The strength of curl is reflected in the second step. You can set the request options flexibly with curl_setopt, there are a lot of options, you can refer to http://cn2.php.net/manual/zh/function.curl-setopt.php
Third, error handling
In the above code, you can also add code for error handling:
Copy the Code code as follows:
$response = curl_exec ($ch);
if ($response = = = FALSE) {
echo "CURL specific error message:". Curl_error ($ch);
}
Note that it is important to use = = = When making the above decision, because the requested reply may be an empty string, and curl returns a false value in case of a request error, so we must use = = = instead of = =.
Iv. obtaining specific information on curl requests
After performing a curl request, you can also use Curl_getinfo to obtain specific information about the request:
Copy the Code code as follows:
Curl_exec ($ch);
$curl _info= Curl_getinfo ($ch);
Echo received the code for the HTTP reply: {$curl _info[' http_code '} ";
The above $curl_info is an associative array from which you can get a lot of specific request information. Reference http://cn2.php.net/manual/zh/function.curl-getinfo.php
V. Send a POST request using Curl
As we said earlier, when sending a GET request to a URL, it is not necessary to use curl to send a GET request, and you can use the more convenient file_get_contents function to complete the request. However, in general, when we submit a form, the data is submitted through the content area of the post request, not through the URL parameters, in which case we should use flexible curl to simulate sending the POST request.
Now let's use curl to simulate sending a POST request to the post.php script, submit several data to post.php, and then output the data in the POST request in post.php. The sample code is as follows:
copy code code as follows:
$url = " Http://www.360weboy.me/post.php ";
$post _data = Array (
"blog_name" = "360weboy",
"blog_url" = "http://www.360weboy.com",
"action" =& Gt "Submit"
);
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, Curlopt_returntransfer, 1);
//Set request for Post type
curl_setopt ($ch, Curlopt_post, 1),
//Add POST data to request
Curl_setopt ($ch, Curlopt_postfields, $post _data);
//Perform POST request, get reply
$response = curl_exec ($ch);
Curl_close ($ch);
Echo $response; After the
request is sent to post.php, the above sample code outputs the following reply after Print_r ($_post):
copy code code is as follows:
Array
(
[blog_name] + 360weboy
[blog_url] =/http Www.360weboy.com
[Action] = Submit
)
As we have seen, Curl successfully sends a POST request to post.php, submits some data, and receives the corresponding reply from post.php, and finally outputs a reply. The above example is simple, but it demonstrates the ease and power of curl sending a POST request, and you can make a fuss on the curl_setopt.
Vi. File Upload
Here's a look at the file upload if you send a POST request via curl. Take the easy-to-use PHP file upload in the file upload example to demonstrate that in the simple way PHP file crosses, is through the form of the submission to achieve file upload, then through curl how to achieve it?
Copy the Code code as follows:
$url = "http://www.360weboy.me/upload.php";
$post _data = Array (
"Attachment" = "@e:/jackblog/boy.jpg"
);
Initializing a Curl session
$ch = Curl_init ();
Set the requested URL
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, Curlopt_returntransfer, 1);
Set to 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 example code above, the boy.jpg on my local machine can be uploaded to the upload.php of the local server, and if the specific information is uploaded on the upload.php output, the reply to the last output of the above example code is:
copy code code is as follows:
Array
(
[ Attachment] = Array
(
[name] = Boy.jpg
[type] + Application/octet-stream
[tmp_name] = d:\x AMPP\TMP\PHPF27D.TMP
[ERROR] + 0
[size] + 11490
)
)
Thus, if you want to upload a file via curl, You only need to set the uploaded file path as post data to the curl request, and precede the path with @.
vii. File Download
The above file upload, you can also use curl to automatically complete the file download and save. One thing to add, when executing a curl request, if you need to get the returned content instead of outputting the returned content directly, don't forget to use the following code settings, because curl defaults to the reply content of the output request:
copy code code as follows:
curl_setopt ($ch, Curlopt_returntransfer, 1);
If there is a test.zip file under the server root directory of 360weboy, we need to download it and save it to a local file, we can try to use the following code to implement:
copy code code is as follows:
//Set the URL of the requested download file
$url = ' http://www.360weboy.com/ Test.zip ';
//Save to local file path
$path = ' local/path/to/test.zip ';
//Initialize the request, set the request, get a reply, close the session
$ch = Curl_init ($url);
curl_setopt ($ch, Curlopt_returntransfer, true);
$data = curl_exec ($ch);
Curl_close ($ch);
//write the contents of the file to a local file
File_put_contents ($path, $data);
Note: I omitted the error-handling aspects of the code, just a simple example, in practice, you also need to pass the Curl_getinfo function to do error handling!
The above code is not suitable for downloading larger files, because the file needs to be read into memory, and all content is read and then written to the local hard disk. Even if the memory limit set in PHP is very large, the effect on performance is significant. So, the download of large files, we should let curl to take over the task, to achieve side download, side write processing, so there is no problem. Take a look at the following code:
Copy the Code code as follows:
$url = ' Http://www.360weboy.com/test.zip ';
$path = ' Local/path/to/test.zip ';
Open Local File
$fp = fopen ($path, ' w ');
Tells the 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 and set the file handle to curl, and then let Curl read the remote data and write it to the local file. Because we do not need to get the contents of the remote reply in the program, we can just execute the request.
Eight, HTTP authentication
If the server side needs to validate the request, it can be done by similar example code:
Copy CodeThe 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 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);
Ix. sending requests by proxy
Curl can also send requests through the proxy server, take a look at the sample code:
Copy CodeThe code is as follows:
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, ' http://www.360weboy.com ');
curl_setopt ($ch, Curlopt_returntransfer, 1);
Set Proxy IP Address
curl_setopt ($ch, Curlopt_proxy, ' 222.73.173.50:8080 ');
To verify this, set the user name and password
curl_setopt ($ch, curlopt_proxyuserpwd, ' Username:password ');
$response = curl_exec ($ch);
Curl_close ($ch);
10. Send JSON data
Finally, let's look at the server-side sending of JSON data through curl. The specific code is as follows:
copy code code is as follows:
$url = '/http/ Www.360weboy.me/json.php ';
//Build JSON string
$data = Array (' site ' = ' 360weboy ', ' 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 above JSON string via 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 my local server json.php, where I use Json_decode to convert the received JSON string to an object, and then output the email field with the following code:
copy code code as follows:
$json _data = Json_decode ($_ post[' data ');
Echo $json _data->email;
The JSON string that is accepted in the preceding code is:
Copy the Code code as follows:
' {' site ': ' 360weboy ', ' url ': ' http:\/\/www.360weboy.com ', ' email ': ' 360weboy@gmail.com '} '
After Json_decode, it is converted to the data format in PHP, becomes an object, so you can access the value of the email field in $json_data->email, and finally the output 360weboy@gmail.com. You can test it with the code above.
If a JSON string is generated from the following PHP array:
Copy the Code code as follows:
$data = Array (' 360weboy ', ' http://www.360weboy.com ', ' 360weboy@gmail.com ');
The resulting JSON string is as follows:
Copy the Code code as follows:
' [' 360weboy ', ' http:\/\/www.360weboy.com ', ' 360weboy@gmail.com '] '
Once the JSON string is json_decode processed, it becomes an array format in PHP and can be accessed via $json_data[2] If you want to get an email.
Xi. Summary
In this article blog post just lists some of the uses of curl, where the sample code is relatively simple. But, I believe you should have the impulse to use curl after reading it! Then you find the relevant information, manual test it!
All right, just write it down here! Thank you for your patience to read!
http://www.bkjia.com/PHPjc/751933.html www.bkjia.com true http://www.bkjia.com/PHPjc/751933.html techarticle The advantages of curl you might say that it's easy to get the content of a URL in PHP, as long as it's easy to implement with File_get_contents,file or ReadFile functions, without having to make ...