Home  >  Article  >  Backend Development  >  Introductory tutorial and common usage examples of curl in php_PHP tutorial

Introductory tutorial and common usage examples of curl in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:34:20948browse

1. Advantages of curl

You may say that it is easy to get the content of a certain URL in php, just through the file_get_contents, file or readfile function. To achieve this, you don’t have to use cURL at all:

Copy the code 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 indeed very convenient to use in some situations, but I feel that these functions are not flexible enough and cannot handle errors. Moreover, if you encounter tasks such as submitting form data to a server, uploading files, processing cookies or authentication in a PHP program, the above three functions are simply not competent. At this time, cURL reflects its value.

cURl not only supports many network protocols, but also provides specific information about url requests, which is very powerful!

2. Simple steps to use curl

To use cURL to send url requests, the specific steps are roughly divided into the following four steps:

1. Initialization
2. Set request options
3. Execute a cURL session and get related replies
4. Release the cURL handle and close a cURL session

Copy code The code is as follows:
 
                                                                                                                                                                                                       . Set request options, including specific url
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 get related responses
, close a cURL session
curl_close($ch);


The reason why cURL is powerful is reflected in the second step. You can flexibly set request options through curl_setopt. There are many options. For details, please refer to http://cn2.php.net/manual/zh/function.curl-setopt.php


3. Error handling

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



Copy code

The code is as follows:

           $response = curl_exec($ch);
if ($response === FALSE) {
echo "cURL specific error message: " . curl_error($ch);
}

Attention, doing the above Be sure to use === when making judgments, because the response to the request may be an empty string, and curl will return a FALSE value if there is an error in the request, so we must use === instead of ==.


4. Get the specific information of the curl request


After executing a cURL request, you can also use curl_getinfo to get the specific information of the request:



Copy code

The code is as follows:

              curl_exec($ch); >            echo "The code of the http reply received is: {$curl_info['http_code']}";

The above $curl_info is an associative array, from which a lot of specific request information can be obtained. Refer to http://cn2.php.net/manual/zh/function.curl-getinfo.php

5. Use curl to send post request

We said before that when sending a get request to a certain URL, there is no need to use cURL to send the get request. You can use comparison Convenience 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 passed through the url parameters. In this case, we should use flexible cURL to simulate sending a post. ask.

Now, let us 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 The 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);

// Set the request to post type
curl_setopt($ch, CURLOPT_POST, 1);
// Add post data to the request
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

// Execute the post request and get the reply
>
After the above request is sent to post.php and output through print_r($_POST), the above example code will output the following reply:



Copy code


The code is as follows:
                                                                                                                                                                                                                                                                        .php reply, and finally output the reply. Although the above example is simple, it fully demonstrates the convenience and power of cURL in sending post requests. You can make a fuss about curl_setopt.
6. File upload


Let’s take a look at how to upload a file by sending a post request through cURL. Let’s take the file upload example in the file upload under PHP in a simple way to demonstrate. In the file upload under PHP in a simple way, the file upload is implemented through the submission of the form. So how to achieve it through cURL?




Copy code

The code is as follows:

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

         $post_data = array (
                                                                                                                                                                                                    . curl_init();

//Set the requested url
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

/ /Set as post request type
curl_setopt($ch, CURLOPT_POST, 1);

//Set specific post data
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

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

print_r($response); Upload boy.jpg on the machine to upload.php on the local server. If the specific upload information is output in upload.php, the final output reply of the above example code is:




Copy code


The code is as follows:

Array ( [attachment] => Array ( [name] => boy.jpg
[type] => application/octet-stream
[tmp_name] => D:xampptmpphpF 27D.tmp
                                                                             0
                                                                                                                                                                                                                    uploaded The file path is set to the curl request as post data, and @ matches is added in front of the path.


7. File download


The above uploaded the file. You can also use curl to automatically download and save the file. One thing to add, when executing a curl request, if you need to obtain the returned content instead of directly outputting the returned content, don't forget to use the following code settings, because curl's default is to output the response content of the request:



Copy code
The code is as follows:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

If there is a test.zip file under the root directory of 360weboy's server, and we need to download it and save it to a local file, we can try to use the following code to achieve it:

Copy code The 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 request, set request, get reply, close session
$ch = curl_init($ url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$data = curl_exec($ch);

curl_close($ch);

/ /Write the file contents to the local file
file_put_contents($path, $data);

Note: I omitted the error handling code above, just to give a simple example. In practice , you also need to handle errors through the curl_getinfo function!

The above code is not suitable for downloading relatively large files, because the file needs to be read into the memory first, and then all the contents are read, and then written to the local hard disk. Even if the memory limit set in PHP is very large, this situation will have a huge impact on performance. Therefore, for downloading large files, we should let curl take over this task and implement downloading and writing at the same time. In this case, there will be no problem. Please look at the following code:

Copy code The code is as follows: .360weboy.com/test.zip ';
$ PATH =' LOCAL/PATH/TOST.ZIP ';

// Open the local file
$ fp = FOPEN ($ PATH, 'w');

// Tell curl the 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 at the same time. Because we don't need to get the content of the remote reply in the program, we just need to execute the request.

8. http verification

If the server needs to verify the request, it can be achieved through a sample code similar to the following:

Copy 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 username and password
curl_setopt($ch, CURLOPT_USERP WD, "username :password");

// Set redirection
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1);

$response = curl_exec($ch);
        curl_close($ch); To send a request to, please take a look at the sample code:



Copy the code
The code is as follows:


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://www.360weboy.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ; Password
curl_setopt($ch, CURLOPT_PROXYUSERPWD,'username:password');

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



10. Sending json data

Finally, let’s take a look at sending json data to the server through cURL. The specific code is as follows:


Copy code

The code is as follows:

$url = 'http://www.360weboy.me/json.php' ;                                                                                                                                                                                                                                   // Create json string email'=>'360weboy@gmail.com');
$json_string = json_encode($data);

$ch=curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1);

//Send the above json string through post request
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, array('data' =>$json_string));

              $response = curl_exec($ch); 
       curl_close($ch); >As you can see, the above request is sent to my local server's json.php. I use json_decode in this file to convert the received json string into an object, and then output the email field in it. The code is as follows:



Copy code

The code is as follows:


$json_data = json_decode($_POST['data']);

echo $json_data->email;
The json string accepted in the above code is:
Copy code

The code is as follows:


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

After json_decode, it is converted into the data format in php and becomes an object, so the value of the email field can be accessed through $json_data->email. Finally That is, the output is 360weboy@gmail.com. You can test it using the above code. If the json string is generated through the following php array:
Copy the code

The code is as follows:

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


The generated json string is as follows: Copy the code
The code is as follows:


                                     360weboy@gmail.com"]'


After being processed by json_decode, the above json string will become an array format in php. If you want to get the email, you can access it through $json_data[2].

11. Summary

In this blog post, we only list some uses of cURL, and the example code is relatively simple. However, I believe you will have the urge to use cURL after reading this! Then go find the relevant information and manuals yourself and test it!

Okay, let’s stop writing here! Thank you for your patient reading!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/751933.htmlTechArticle1. Advantages of curl You may say that you can easily obtain the content of a certain URL in php. It can be easily achieved through the file_get_contents, file or readfile function. There is no need to use...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn