Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use curl in php

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to use curl in php". In daily operation, I believe many people have doubts about how to use curl in php. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use curl in php". Next, please follow the editor to study!

I. advantages of curl

You might say that you can easily get the contents of a url in php, as long as you can do it through the file_get_contents,file or readfile function, without having to use cURL at all:

The copy 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 convenient to use in some cases, but I feel that these functions are not flexible enough to handle errors. Moreover, if you have to submit form data, upload files, process cookies or authenticate to a server 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 for using curl

To use cURL to send an url request, the steps are roughly as follows:

1. Initialization

two。 Set request options

3. Execute a cURL session and get a reply

4. Release the cURL handle and close a cURL session

The copy code is as follows:

/ / 1. Initialize a cURL session

$ch = curl_init ()

/ / 2. 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 a reply

$response = curl_exec ($ch)

/ / 4. Release the cURL handle and 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 more information, please see http://cn2.php.net/manual/zh/function.curl-setopt.php.

III. Error handling

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

The copy code is as follows:

$response = curl_exec ($ch)

If ($response = FALSE) {

Echo "cURL specific error message:". Curl_error ($ch)

}

Note that when making the above judgment, be sure to use = =, because the reply to the request may be an empty string, and curl returns a false value if the request goes wrong, so we must use = = instead of = =.

4. Obtain the specific information of curl request

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

The copy code is as follows:

Curl_exec ($ch)

$curl_info= curl_getinfo ($ch)

Echo "received http reply with the code of: {$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

Use curl to send post request

As we said earlier, when sending a get request to a url, there is no need to use cURL to send the get request, 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 parameter, 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 pieces of data to post.php, and then output the data from the post request in post.php. The sample code is as follows:

The copy 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 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 a reply

$response= curl_exec ($ch)

Curl_close ($ch)

Echo $response

After the above request is sent to post.php and output via print_r ($_ POST), the above sample code will output the following reply:

The copy 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, receives a corresponding reply from post.php, and finally outputs a reply. Although the above example is simple, it fully demonstrates the convenience and power of sending post requests from cURL. You can write about it on curl_setopt.

VI. File upload

Let's take a look at how to upload a file by sending a post request through cURL. Take the file upload example in the file upload under PHP to demonstrate, in the file upload under php, the file upload is achieved through the submission of the form, so how to achieve file upload through cURL?

The copy code is as follows:

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

$post_data = array (

"attachment" > "@ E:/jackblog/boy.jpg"

);

/ / initialize 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 specific post data

Curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_data)

$response = curl_exec ($ch)

Curl_close ($ch)

Print_r ($response)

Through the above sample code, you can upload the boy.jpg on my local machine to the upload.php of the local server. If the specific information of the upload is output in upload.php, the final output of the above sample code is as follows:

The copy 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

)

)

Thus, if you want to upload files through cURL, just set the path of the uploaded file to the curl request as post data and precede the path with @ match.

VII. File download

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

The copy code is as follows:

Curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1)

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

The copy code is as follows:

/ / set the url of the requested download file

$url = 'http://www.360weboy.com/test.zip';

/ / Save to the local file path

$path = 'local/path/to/test.zip'

/ / initialize the request, set the request, get a 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 contents to the local file

File_put_contents ($path, $data)

Note: I omitted the error handling code above, just to do a simple example, in practice, you also need to use the curl_getinfo function for error handling!

The above code is not applicable for downloading larger files, because you need to read the file into memory first, wait for everything to be read, and then write to the local hard disk. Even if the memory limit set in php is very large, this situation has a significant impact on performance. Therefore, for the download of large files, we should let curl take over the task and implement the processing of downloading and writing at the same time. In that case, there will be no problem. Please look at the following code:

The copy code is as follows:

$url = 'http://www.360weboy.com/test.zip';

$path = 'local/path/to/test.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, set the file handle to curl, and then let curl read the remote data while writing to the local file. Because we no longer need to get the content of the remote reply in the program, we just need to execute the request.

VIII. Http verification

If the server side needs to validate the request, you can do so by similar to the following sample code:

The copy 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. Send a request through an agent

CURL can also send requests to the proxy server. Take a look at the sample code:

The copy 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 purl 8080')

/ / to verify, set the user name 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 sending json data to the server through cURL. The specific code is as follows:

The copy code is as follows:

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

/ / create a json string

$data = array ('site' = >' 360 weboyboy, '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 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)

Echo $response

You can see that the above request is sent to the json.php of my local server. In this file, I use json_decode to convert the received json string into an object, and then output the email field as follows:

The copy code is as follows:

$json_data = json_decode ($_ POST ['data'])

Echo $json_data- > email

The json string accepted in the above code is:

The copy code is 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 and becomes an object, so you can access the value of the email field through $json_data- > email, and finally output 360weboy@gmail.com. You can test it with the above code.

If the json string is generated from the following php array:

The copy code is as follows:

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

The generated json string is as follows:

The copy code is as follows:

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

After json_decode processing, the above json string becomes an array format in php, and if you want to get the email, you can access it through $json_data [2].

At this point, the study on "how to use curl in php" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report