Curl Learning to save

Source: Internet
Author: User

Label:

Original address

Http://www.jb51.net/article/48866.htm

Curl in PHP Getting Started tutorial and common usage instance fonts: [Increase decrease] type: Reprint

At first Curl was designed as a command-line tool, and fortunately, PHP also supports curl. With curl, we can freely send HTTP requests to a URL to fetch or submit data in a PHP program, and support many other protocols such as Ftp,telnet and SMTP. In this post, I'll briefly describe how curl is used in PHP to handle things.

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 CodeThe code is 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 CodeThe code is 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 CodeThe code is 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 CodeThe code is as follows:

$url = "http://www.360weboy.me/post.php";

$post _data = Array (
"Blog_name" = "360weboy",
"Blog_url" = "http://www.360weboy.com",
"Action" = "Submit"
);

$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, Curlopt_returntransfer, 1);

Set request to post type
curl_setopt ($ch, Curlopt_post, 1);
Add post data to the request
curl_setopt ($ch, Curlopt_postfields, $post _data);

Perform a POST request to get a reply
$response = curl_exec ($ch);
Curl_close ($ch);

Echo $response;


After the above request is sent to post.php, the above sample code outputs the following reply after Print_r ($_post) Output:
Copy CodeThe code is as follows:

Array
(
[Blog_name] = 360weboy
[Blog_url] = http://www.360weboy.com
[Action] = Submit
)
As we can see, 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 CodeThe code is 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 CodeThe code is as follows:
Array
(
[Attachment] = = Array
(
[Name] = Boy.jpg
[Type] = Application/octet-stream
[Tmp_name] = D:\xampp\tmp\phpF27D.tmp
[ERROR] = 0
[Size] = 11490
)

)

This shows that 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. Download of documents

The above will upload the file, the same 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 CodeThe code is 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 CodeThe 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 a request, set a request, get a reply, close a session
$ch = Curl_init ($url);
curl_setopt ($ch, Curlopt_returntransfer, true);

$data = curl_exec ($ch);

Curl_close ($ch);

Write file contents to 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 CodeThe code is 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 CodeThe code is as follows:
$url = ' http://www.360weboy.me/json.php ';

Creating a JSON string
$data = Array (' site ' = ' 360weboy ', ' url ' = ' http://www.360weboy.com ', ' email ' = ' [email protected] ');
$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 under 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 CodeThe code is as follows:

$json _data = Json_decode ($_post[' data ');

Echo $json _data->email;


The JSON string that is accepted in the preceding code is:
Copy CodeThe code is as follows:

' {' site ': ' 360weboy ', ' url ': ' http:\/\/www.360weboy.com ', ' email ': ' [email protected] '} '
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 through $json_data->email, and finally the output [email protected]. You can test it with the code above.

If a JSON string is generated from the following PHP array:

Copy CodeThe code is as follows:

$data = Array (' 360weboy ', ' http://www.360weboy.com ', ' [email protected] ');
The resulting JSON string is as follows:
Copy CodeThe code is as follows:

' [360weboy ', ' http:\/\/www.360weboy.com ', ' [email protected] '
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

Curl Learning to save

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: