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

Source: Internet
Author: User
Tags error handling file upload ftp how to use curl http authentication http cookie http post php and
At first cURL was designed as a command line tool. Fortunately, PHP also supports cURL. With the cURL tool, we can freely send HTTP requests to a url in a PHP program to obtain or submit data, and support other multiple protocols, such as FTP, Telnet, and SMTP. In this blog post, I will briefly describe how to use cURL to handle some things in PHP.

First, the advantages of curl

You might say that you can easily get the content of a certain URL in PHP, as long as you use file_get_contents, file or readfile function, you don't need to use cURL at all:

Copy the code:

$ 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 cases, but I feel that these functions are not flexible enough and cannot handle error handling. Moreover, 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 capable. 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!

Second, the simple use of curl

To use cURL to send a URL request, the specific steps are roughly divided into the following four steps:

Initialization

2. Set request options

3. Execute a cURL session and get related responses

4. Release the cURL handle and close a cURL session

Copy the code:

// 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 the relevant 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 available. For details, please refer to http://cn2.php.net/manual/en/function.curl-setopt.php

Third, error handling

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

Copy the code:

$ response = curl_exec ($ ch);

if ($ response === FALSE) {

echo "cURL specific error message:". curl_error ($ ch);

}

Note that you must use === when making the above judgment, because the response to the request may be an empty string, and curl returns a FALSE value in the case of an error in the request, so we must use === instead of ==.

Fourth, 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 the code:

curl_exec ($ ch);

$ curl_info = curl_getinfo ($ ch);

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

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

Five, use curl to send post requests

We said earlier 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 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, rather than passed through the url parameter. In this case, we should use flexible cURL to simulate sending a post request.

Now, let's use cURL to simulate sending a post request to a post.php script, submitting a few data to post.php, and then output the data in the post request in post.php. The sample code is as follows:

Copy the code:

$ 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

curl_setopt ($ ch, CURLOPT_POST, 1);

// Add post data to the request

curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post_data);

// execute post request and get reply

$ response = curl_exec ($ ch);

curl_close ($ ch);

echo $ response;

After sending the above request to post.php and outputting it through print_r ($ _ POST), the above example code will output the following response:

Copy the code:

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 a corresponding response from post.php, and finally outputs a response. Although the above example is simple, it fully demonstrates the convenience and power of cURL to send post requests. You can do an article on curl_setopt.

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 explain in simple language, in the file upload under PHP to explain the file upload through the form submission, then how to achieve through cURL?

Copy the code:

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

$ post_data = array (

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

);

// Initiate a cURL session

$ ch = 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);

Through the above example code, boy.jpg on my local machine can be uploaded to upload.php on the local server. If the uploading specific information is uploaded in upload.php, the final output of the above example code is:

Copy the code:

Array

(

[attachment] => Array

(

[name] => boy.jpg

[type] => application / octet-stream

[tmp_name] => D: \ xampp \ tmp \ phpF27D.tmp

[error] => 0

[size] => 11490

)

)

It can be seen that if you want to upload files through cURL, you only need to set the uploaded file path as post data in the curl request, and add @match in front of the path.

File download



The above uploads files. Similarly, you can use curl to download and save files automatically. 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, don't forget to use the following code setting, because the default of curl is to output the response content of the request:

Copy the code:

curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1);

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

Copy the code:

// 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 a local file

file_put_contents ($ path, $ data);

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

The above code is not suitable for downloading large 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 great impact on performance. Therefore, for the download of large files, we should let curl take over this task, and realize the processing of downloading and writing at the same time, so there is no problem. Consider the following code:

Copy the code:

$ 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 and write to the local file. Because we don't need to get the content of the remote reply in the program, we just need to execute the request.

Eight, http authentication



If the server needs to verify the request, it can be implemented by the following sample code:

Copy the code:

$ 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_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 a request through a proxy



cURL can also send requests through a proxy server, please take a look at the sample code:

Copy the code:

$ 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 username and password here

curl_setopt ($ ch, CURLOPT_PROXYUSERPWD, 'username: password');

$ response = curl_exec ($ ch);

curl_close ($ ch);

Ten, send json data



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

Copy the code:

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

// create 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 through a 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. 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 the code:

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

echo $ json_data-> email;

The json string accepted in the above code is:

Copy the code:

'{"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 you can access the value of the email field through $ json_data-> email, and finally output 360weboy@gmail.com. You can use the above code to test it.

If you generate the json string from the following php array:

Copy the code:

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

The generated json string is as follows:

Copy the code:

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

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

Some parameter references

The following option values will be used as long integers (specified in the option parameter):

CURLOPT_INFILESIZE: When you upload a file to a remote site, this option tells PHP the size of your uploaded file.

CURLOPT_VERBOSE: If you want CURL to report every unexpected event, set this option to a non-zero value.

CURLOPT_HEADER: If you want to include a header in the output, set this option to a non-zero value.

CURLOPT_NOPROGRESS: If you do not want PHP to display a progress bar for CURL transfers, set this option to a non-zero value.

Note: PHP automatically sets this option to a non-zero value. You should change this option just for debugging purposes.

CURLOPT_NOBODY: If you don't want to include a body part in the output, set this option to a non-zero value.

CURLOPT_FAILONERROR: If you want PHP to not display when an error occurs (HTTP code returns 300 or greater), set this option to a non-zero value for one person. The default behavior is to return a normal page, ignoring the code.

CURLOPT_UPLOAD: If you want PHP to prepare for upload, set this option to a non-zero value.

CURLOPT_POST: If you want PHP to do a regular HTTP POST, set this option to a non-zero value. This POST is a normal application / x-www-from-urlencoded type and is mostly used by HTML forms.

CURLOPT_FTPLISTONLY: Set this option to a non-zero value. PHP will list FTP directory names.

CURLOPT_FTPAPPEND: Set this option to a non-zero value and PHP will apply the remote file instead of overwriting it.

CURLOPT_NETRC: Set this option to a non-zero value. PHP will look in your ~. / Netrc file for the username and password of the remote site you want to establish a connection with.

CURLOPT_FOLLOWLOCATION: Set this option to a non-zero (like `` Location: '') header, and the server will send it as part of the HTTP header (note that this is recursive, PHP will send a header that looks like `` Location: '').

CURLOPT_PUT: Set this option to a non-zero value to upload a file using HTTP. To upload this file, the CURLOPT_INFILE and CURLOPT_INFILESIZE options must be set.

CURLOPT_MUTE: Set this option to a non-zero value. PHP will be completely silent on CURL functions.

CURLOPT_TIMEOUT: Set a long integer as the maximum number of seconds to continue.

CURLOPT_LOW_SPEED_LIMIT: Set a long integer to control how many bytes are transmitted.

CURLOPT_LOW_SPEED_TIME: Set a long integer to control how many seconds the CURLOPT_LOW_SPEED_LIMIT byte is transmitted.

CURLOPT_RESUME_FROM: Pass a long parameter containing the byte offset address (the start form you want to transfer to).

CURLOPT_SSLVERSION: Pass a long parameter containing the SSL version. The default PHP will be determined by its own efforts, you must set it manually for more security.

CURLOPT_TIMECONDITION: Pass a long parameter specifying how to handle the CURLOPT_TIMEVALUE parameter. You can set this parameter to TIMECOND_IFMODSINCE or TIMECOND_ISUNMODSINCE. This is only used for HTTP.

CURLOPT_TIMEVALUE: Pass a number of seconds from 1970-1-1 to the present. This time will be used by the CURLOPT_TIMEVALUE option as the specified value, or by the default TIMECOND_IFMODSINCE.

The values of the following options are treated as strings:

CURLOPT_URL: This is the URL you want to retrieve with PHP. You can also set this option when initializing with the curl_init () function.

CURLOPT_USERPWD: Pass a string of the form [username]: [password], and use PHP to connect.

CURLOPT_PROXYUSERPWD: Pass a string of the form [username]: [password] to connect to the HTTP proxy.

CURLOPT_RANGE: Pass a range you want to specify. It should be in 'X-Y' format, with X or Y being excluded. HTTP transmission also supports several intervals, separated by commas (X-Y, N-M).

CURLOPT_POSTFIELDS: Pass a string of all data as an HTTP "POST" operation.

CURLOPT_REFERER: A string containing a 'referer' header in the HTTP request.

CURLOPT_USERAGENT: A string containing a 'user-agent' header in the HTTP request.

CURLOPT_FTPPORT: Pass an IP address containing the IP address used by the ftp 'POST' command. This POST instruction tells the remote server to connect to the IP address we specified. This string can be an IP address, a host name, a network interface name (under UNIX), or '-' (use the system default IP address).

CURLOPT_COOKIE: Pass a header connection containing an HTTP cookie.

CURLOPT_SSLCERT: Pass a string containing a PEM format certificate.

CURLOPT_SSLCERTPASSWD: Pass a password that contains the necessary credentials to use the CURLOPT_SSLCERT certificate.

CURLOPT_COOKIEFILE: Pass a string containing the name of the file containing the cookie data. This cookie file can be in Netscape format or HTTP-style headers stored in a file.

CURLOPT_CUSTOMREQUEST: When making an HTTP request, pass a character to be used by GET or HEAD. For DELETE or other operations, it is beneficial to pass a string to be used instead of GET or HEAD when doing an HTTP request. This is useful for doing or another, more obscure, HTTP request.

Note: Do not do this before confirming that your server supports commands.

The following options require a file description (obtained by using the fopen () function):

CURLOPT_FILE: This file will be the output file you placed for transmission. The default is STDOUT.

CURLOPT_INFILE: This file is the input file you transmitted.

CURLOPT_WRITEHEADER: This file contains the header part of your output.

CURLOPT_STDERR: This file was written with errors instead of stderr.
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.