Php CURL function tutorials

Source: Internet
Author: User
Tags curl error handling file upload ftp http authentication remote ftp server

CURL introduction

CURL is a tool that uses the URL syntax to transmit data and files. It supports many protocols, such as HTTP, FTP, and TELNET. PHP also supports the cURL Library.


If we want to obtain the content of a webpage, we may use the following methods:

The code is as follows: Copy code


<? Php
// Read the entire file into a string
$ Str = file_get_contents ("http://www.111cn.net ");

// Read the entire file into an array
$ Arr = file ("http://www.111cn.net ");

// Read a file and write it to the output buffer
$ Out = readfile ("http://www.111cn.net ");
?>


 

These methods are quite simple, but lack flexibility and effective error handling. In addition, they cannot perform difficult operations, such as coockies processing, verification, form submission, and file upload.


CURL example

Below is a simple piece of code, from which you can learn the general steps of using cURL, php cURL Getting Started Tutorial.

The code is as follows: Copy code

 

<? Php
Header ("Content-type: text/html; charset = utf-8 ");

// 1. Initialization
$ Ch = curl_init ();

// 2. Set options
Curl_setopt ($ ch, CURLOPT_URL, "http://www.111cn.net ");
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_HEADER, 0 );

// 3. Execute and obtain the returned content
$ Output = curl_exec ($ ch );

// 4. Error judgment. Note that this is a Boolean value, rather than an empty output, so it is a three equal sign.
If ($ output = FALSE ){
Echo "cURL Error:". curl_error ($ ch );
}

// 5. Release curl resources
Curl_close ($ ch );

// Output the source code
Echo $ output;
?>


The curl_setopt () in the second step is the most important. There is a long string of cURL parameters that can be set to specify the details of URL requests.


Obtain information

This is another optional setting item, which can obtain the relevant information of this request after the cURL is executed:

The code is as follows: Copy code

 

<? Php
Header ("Content-type: text/html; charset = utf-8 ");

// 1. Initialization
$ Ch = curl_init ();

// 2. Set options
Curl_setopt ($ ch, CURLOPT_URL, "http://www.111cn.net ");
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_HEADER, 0 );

// 3. Execute and obtain the HTML document content
$ Output = curl_exec ($ ch );

// 4. Error judgment. Note that this is a Boolean value, rather than an empty output, so it is a three equal sign.
If ($ output = FALSE ){
Echo "cURL Error:". curl_error ($ ch );
}

// Obtain and output cURL information
$ Info = curl_getinfo ($ ch );
Echo 'get '. $ info ['URL'].' time consumed '. $ info ['total _ time']. 'Second ';

// 5. Release the curl handle
Curl_close ($ ch );
?>


The returned array contains the following information:


"Url" // resource network address
"Content_type" // content type and encoding
"Http_code" // HTTP status code
"Header_size" // header size
"Request_size" // request size
"Filetime" // file creation time
"Ssl_verify_result" // SSL verification result
"Redirect_count" // jump Technology
"Total_time" // total time consumed
"Namelookup_time" // DNS query time
"Connect_time" // waiting for connection time
"Pretransfer_time" // pre-transmission preparation time
"Size_upload" // size of the uploaded data
"Size_download" // size of the downloaded data
"Speed_download" // download speed
"Speed_upload" // upload speed
"Download_content_length" // length of the downloaded content
"Upload_content_length" // length of the uploaded content
"Starttransfer_time" // start time of transmission
"Redirect_time" // time consumed by redirection

 

Use the POST method to send data

Create from. php

The code is as follows: Copy code


<? Php
Header ("Content-type: text/html; charset = utf-8 ");

// Data to be post
$ Post_data = array (
"Hyh" => "man ",
"Xlp" => "woman ",
"Love" => "yes"
);

// 1. Initialization
$ Ch = curl_init ();

// 2. Set options
Curl_setopt ($ ch, CURLOPT_URL, "http: // localhost/to. php ");
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_POST, 1); // Set it to post
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post_data); // add the data for post preparation.

// 3. Execute and obtain the returned content
$ Output = curl_exec ($ ch );

// 4. Error judgment. Note that this is a Boolean value, rather than an empty output, so it is a three equal sign.
If ($ output = FALSE ){
Echo "cURL Error:". curl_error ($ ch );
}

// 5. Release the curl handle
Curl_close ($ ch );

// Output Content
Echo $ output;
?>


 

Create to. php

The code is as follows: Copy code


<? Php
Header ("Content-type: text/html; charset = utf-8 ");

Echo "data from. php POST to. php is successful! The data returned by to. php is as follows: <br> ";
Print_r ($ _ POST );
Echo "<br> I'm come from http://www.111cn.net"
?>


 


File Upload

The upload file is very similar to the previous POST, because all file upload forms are submitted through the POST method.

Create from. php

The code is as follows: Copy code


<? Php
Header ("Content-type: text/html; charset = utf-8 ");

// Data to be post
$ Post_data = array (
"Hyh" => "man ",
"Upload" => "@ C:/test.zip" // address of the local file to be uploaded
);

// 1. Initialization
$ Ch = curl_init ();

// 2. Set options
Curl_setopt ($ ch, CURLOPT_URL, "http: // localhost/to. php ");
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_POST, 1); // Set it to post
Curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post_data); // add the data for post preparation.

// 3. Execute and obtain the returned content
$ Output = curl_exec ($ ch );

// 4. Error judgment. Note that this is a Boolean value, rather than an empty output, so it is a three equal sign.
If ($ output = FALSE ){
Echo "cURL Error:". curl_error ($ ch );
}

// 5. Release curl resources
Curl_close ($ ch );

// Output Content
Echo $ output;
?>


 

Create to. php:

The code is as follows: Copy code


<? Php
Header ("Content-type: text/html; charset = utf-8 ");

Print_r ($ _ FILES );
?>


If you need to upload a file, you only need to pass the file path like a post variable, but remember to add the @ symbol before it.

Other useful cURL examples

HTTP authentication

If a URL request requires HTTP-based authentication, you can use the following code:

The code is as follows: Copy code

 

<? Php
Header ("Content-type: text/html; charset = utf-8 ");

// 1. Initialization
$ Ch = curl_init ();

// 2. Set options
Curl_setopt ($ ch, CURLOPT_URL, "http://www.111cn.net ");
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_USERPWD, "myusername: mypassword"); // send the user name and password
Curl_setopt ($ ch, CURLOPT_FOLLOWLOCATION, 1); // you can allow redirection.
Curl_setopt ($ ch, CURLOPT_UNRESTRICTED_AUTH, 1); // after cURL is redirected, the user name and password can also be sent.

// 3. Execute and obtain the returned content
$ Output = curl_exec ($ ch );

// 4. Error judgment. Note that this is a Boolean value, rather than an empty output, so it is a three equal sign.
If ($ output = FALSE ){
Echo "cURL Error:". curl_error ($ ch );
}

// 5. Release the curl handle
Curl_close ($ ch );
?>


FTP Upload

PHP has an FTP class library, but you can also use cURL. You can also refer to this article: php uses cURL to implement ftp upload.

 

The code is as follows: Copy code

<? Php
Header ("Content-type: text/html; charset = utf-8 ");

// Open a file pointer
$ File = fopen ("/path/to/file", "r ");

// 1. Initialization
$ Ch = curl_init ();

// 2. Set options
Curl_setopt ($ ch, CURLOPT_URL, "ftp: // username: password@3aj.cn: 21/path/to/new/file ");
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
// Upload related options
Curl_setopt ($ ch, CURLOPT_UPLOAD, 1 );
Curl_setopt ($ ch, CURLOPT_INFILE, $ fp );
Curl_setopt ($ ch, CURLOPT_INFILESIZE, filesize ("/path/to/file "));
// Whether to enable the ASCII mode (used when uploading text files)
Curl_setopt ($ ch, CURLOPT_FTPASCII, 1 );

// 3. Execute and obtain the returned content
$ Output = curl_exec ($ ch );

// 4. Error judgment. Note that this is a Boolean value, rather than an empty output, so it is a three equal sign.
If ($ output = FALSE ){
Echo "cURL Error:". curl_error ($ ch );
}

// 5. Release the curl handle
Curl_close ($ ch );
?>


 

You can use a proxy to initiate a cURL request:

The code is as follows: Copy code

<? Php
Header ("Content-type: text/html; charset = utf-8 ");

// 1. Initialization
$ Ch = curl_init ();

// 2. Set options
Curl_setopt ($ ch, CURLOPT_URL, "http://www.111cn.net ");
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_PROXY, '11. 11.11.11: 8080 '); // specify the proxy address
Curl_setopt ($ ch, CURLOPT_PROXYUSERPWD, 'User: pass'); // provide the user name and password if needed

// 3. Execute and obtain the returned content
$ Output = curl_exec ($ ch );

// 4. Error judgment. Note that this is a Boolean value, rather than an empty output, so it is a three equal sign.
If ($ output = FALSE ){
Echo "cURL Error:". curl_error ($ ch );
}

// 5. Release the curl handle
Curl_close ($ ch );
?>


 

Callback function


CURL can call a specified callback function during a URL request. For example, you can use data immediately during content or response download, instead of waiting until the download is complete.

The code is as follows: Copy code

 

<? Php
Header ("Content-type: text/html; charset = utf-8 ");

// 1. Initialization
$ Ch = curl_init ();

// 2. Set options
Curl_setopt ($ ch, CURLOPT_URL, "http://www.111cn.net ");
Curl_setopt ($ ch, CURLOPT_WRITEFUNCTION, "progress_function ");

// 3. Execute and obtain the returned content
Curl_exec ($ ch );

// 4. Error judgment. Note that this is a Boolean value, rather than an empty output, so it is a three equal sign.
If ($ output = FALSE ){
Echo "cURL Error:". curl_error ($ ch );
}

// 5. Release the curl handle
Curl_close ($ ch );

// Callback function
Function progress_function ($ ch, $ str ){
Echo $ str;
Return strlen ($ str );
}
?>


 

This callback function must return the length of the string. Otherwise, this function will not work properly. During The URL response receiving process, this function will be called as long as a packet is received.

After talking about this for half a day, we will use the cURL feature of the advanced practical point to implement ftp upload.

Web server Upload restrictions:

Php's default upload limit is 2 MB. If you want to upload files larger than 2 MB, you must modify your PHP configuration or use the following code to create a. htaceess file.

The code is as follows: Copy code

Php_value upload_max_filesize 16 M
Php_value post_max_size 20 M


Here, the maximum file upload limit is 16 MB, and the value of post_max_size is 20 MB, because we may need the values of other Form items in the POST form while uploading the file.
The created. htaccess should be placed in the same directory as your Upload script.

Use cURL to upload files

CURL is a tool that uses URL syntax to transmit files and data. It supports many protocols, such as HTTP, FTP, and TELNET. It can complete many difficult tasks, such as coockies processing, verification, form submission, file upload, ftp upload, and so on.

Here, we are going to upload a file to the ftp space by using a web form. The ftp space here is password-protected.

The code is as follows: Copy code

<Form action = "curlupload. php" method = "post" enctype = "multipart/form-data">
<Div>
<Label for = "upload"> Select file </label>
<Input name = "upload" type = "file"/>
<Input type = "submit" name = "Submit" value = "Upload"/>
</Div>
</Form>

This form page is relatively simple and only has a file upload function.
Then we need the following php code to receive the uploaded files, use cURL to open a file stream and send it to the remote ftp server.

The code is as follows: Copy code


If (isset ($ _ POST ['submit ']) {
If (! Empty ($ _ FILES ['upload'] ['name']) {
$ Ch = curl_init ();
$ Localfile = $ _ FILES ['upload'] ['tmp _ name'];
$ Fp = fopen ($ localfile, 'r ');
Curl_setopt ($ ch, CURLOPT_URL, 'ftp: // username: password@3aj.cn/'. $ _ FILES ['upload'] ['name']);
Curl_setopt ($ ch, CURLOPT_UPLOAD, 1 );
Curl_setopt ($ ch, CURLOPT_INFILE, $ fp );
Curl_setopt ($ ch, CURLOPT_INFILESIZE, filesize ($ localfile ));
Curl_exec ($ ch );
$ Error_no = curl_errno ($ ch );
Curl_close ($ ch );
If ($ error_no = 0 ){
$ Error = 'File uploaded succesfully .';
} Else {
$ Error = 'File upload error .';
Echo "I come from ";
        }
} Else {
$ Error = 'Please select a file .';
    }
}


 

When the user selects and uploads a file, the file is saved on the web server first. We use fopen to open the temporary file and initiate a cURL session. In the sent url, fill in the ftp account and password, and then set other necessary parameters of cURL. If the number of returned errors is 0, the file is uploaded successfully.


Summary

Today, we learned the powerful functions and flexible scalability of the cURL Library from: 3a tutorial network.

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.