Curl in PHP using the Getting Started tutorial and examples of common usages _php

Source: Internet
Author: User
Tags curl http authentication php file upload php script readfile

First, the advantages of curl

You might say that in PHP you can easily get the content of a URL, as long as through the File_get_contents,file or ReadFile function can be easily implemented, do not have to use the curl:

Copy Code code 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 to 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 authenticating, the above three functions are simply not competent. At 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!

Second, the simple use of curl steps

To use Curl to send URL requests, the steps are generally divided into the following four steps:

1. Initialize
2. Set Request options
3. Execute a Curl session and get the relevant reply
4. Release the curl handle and close a curl session

Copy Code code 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. 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 reason why curl is strong is reflected in the second step. You can set the request options flexibly through curl_setopt, which has a lot of options, specific reference to http://cn2.php.net/manual/zh/function.curl-setopt.php

Third, error handling

In the above code, you can also increase the error handling code:

Copy Code code as follows:


$response = curl_exec ($ch);

if ($response = = FALSE) {
echo "CURL specific error message:". Curl_error ($ch);
}


Note that you must use = = = When making this judgment, because the requested reply may be an empty string, curl returns false value in case of a request error, so we have to use = = = instead of = =.

Iv. obtaining specific information for Curl requests

After executing a curl request, you can also use Curl_getinfo to obtain specific information about the request:

Copy Code code as follows:


Curl_exec ($ch);
$curl _info= Curl_getinfo ($ch);

echo "received an HTTP reply with the code: {$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 you send a GET request to a URL, it is not necessary to use curl to send a got request, and you can use the more convenient file_get_contents function to complete the request. However, generally, when we submit a form, the data is submitted through the content area of the post request, rather than through the URL parameter, in which case we should use a 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" => "Submit"
);

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

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

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

Echo $response;


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


Array
(
[Blog_name] => 360weboy
[Blog_url] => http://www.360weboy.com
[Action] => Submit
)

As we can see, Curl successfully sent the POST request to post.php, submitted some data, and received the corresponding reply from post.php, the final output reply. The example above is simple, but it fully demonstrates the curl and power of sending post requests, and you can make a fuss over curl_setopt.

Six, File Upload

Let's see if you can upload the file by sending a POST request via curl. Take a simple php file upload in the file upload example to demonstrate, in the easy PHP file on the cross, is through the form of submission to achieve file upload, then through the curl how to achieve it?

Copy 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 URL of the request
curl_setopt ($ch, Curlopt_url, $url);
curl_setopt ($ch, Curlopt_returntransfer, 1);

Set to POST request type
curl_setopt ($ch, Curlopt_post, 1);

To set 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 the boy.jpg on my local machine to the local server upload.php, if the specific information uploaded in upload.php output, the last output of the above example code is as follows:

Copy Code code 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 files via curl, you simply have to set the uploaded file path as post data to the curl request, and precede the path with @ compliance.

Vii. File Download

The above will upload the file, the same can also use curl to automatically complete the file download and save. One thing to add is that when executing a curl request, if you need to get the returned content instead of directly outputting the returned content, do not forget to use the following code settings, because the curl default is the output request reply content:

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 as follows:


Set the URL of the requested download file
$url = ' Http://www.360weboy.com/test.zip ';

Save to a local file path
$path = ' Local/path/to/test.zip ';

Initialize the request, set the request, get the 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 a file to a local file
File_put_contents ($path, $data);

Note: I have omitted the error handling code, but simply to do an example, in practice, you also need to pass the Curl_getinfo function for error handling!

The above code does not apply to downloading larger files because you need to read the files to memory before all the content is read and then written to the local hard disk. Even though the memory limit set in PHP is very large, this situation has a significant impact on performance. Therefore, we for large file download, should let curl to take over this task, implementation side download, edge write processing, so, then there is no problem. Please see the following code:

Copy Code code as follows:


$url = ' Http://www.360weboy.com/test.zip ';
$path = ' Local/path/to/test.zip ';

Open 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 the remote data while writing to the local file. Because we don't need to get the content of the remote reply in the program, we can just execute the request.

Eight, HTTP authentication

If the server side requires authentication requests, you can do so by using a similar sample code:

Copy Code code 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 redirect
curl_setopt ($ch, curlopt_followlocation, 1);
curl_setopt ($ch, Curlopt_unrestricted_auth, 1);

$response = curl_exec ($ch);
Curl_close ($ch);

Nine, send the request through the agent

Curl can also send a request through a proxy server, take a look at the sample code:
Copy Code code 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, set the username and password here
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 the curl to send JSON data to the server side. The specific code is as follows:

Copy Code code as follows:

$url = ' http://www.360weboy.me/json.php ';

Create a 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 under the json.php, where I use Json_decode to convert the received JSON string into an object, and then output the email field in 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 Code code as follows:


' {site ': "360weboy", "url": "http:\/\/www.360weboy.com", "email": "360weboy@gmail.com"} '

After Json_decode, the conversion to the data format in PHP, became an object, so you can access through $json_data->email to the value of the email field, the last is the output of 360weboy@gmail.com. You can use the above code to test.

If you generate a JSON string from the following PHP array:

Copy Code code as follows:


$data = Array (' 360weboy ', ' http://www.360weboy.com ', ' 360weboy@gmail.com ');

The generated JSON string is as follows:
Copy Code code as follows:


' [360weboy ', ' http:\/\/www.360weboy.com ', ' 360weboy@gmail.com '] '

The above JSON string, after json_decode processing, 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 posting just enumerated some of the curl uses, where the sample code is relatively simple. However, I believe you should have the impulse to use curl after reading it! Then go to find the relevant information, Manual for testing it!

All right, just write it down here! Thank you for your patience to read!

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.