Getting started with curl in php and common usage example _ php instance

Source: Internet
Author: User
Tags how to use curl response code
At first, cURL was designed as a command line tool. Fortunately, php also supports cURL. With 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, Telnet, and SMTP. In this blog post, I will briefly describe how to use cURL in php to handle some things. 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!

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.

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.