PHP Curl function Getting Started tutorial detailed _php tutorial

Source: Internet
Author: User
Tags http authentication remote ftp server
In PHP, the Curl function has a set of related functions, it is a very good function, we often use it to imitate a variety of login and collection work, let me introduce you to the Curl function get started.

About Curl

Curl is a tool that uses URL syntax to transfer data and files, and supports a wide variety of protocols such as HTTP, FTP, Telnet, and so on. PHP also supports the CURL library.


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

The code is as follows Copy Code


Read the entire file into a string
$str = file_get_contents ("http://www.bKjia.c0m");

To read an entire file into an array
$arr = File ("http://www.bKjia.c0m");

Read in a file and write to the output buffer
$out = ReadFile ("http://www.bKjia.c0m");
?>


These approaches are fairly simple, but lack flexibility and effective error handling. And they are unable to perform some of the most difficult actions, such as handling coockies, validation, form submissions, file uploads, and so on.


Curl Simple Example

Here's a simple code, from which you can learn the approximate steps of using curl, the PHP Curl Primer tutorial.

The code is as follows Copy Code

Header ("content-type:text/html; Charset=utf-8 ");

1. Initialization
$ch = Curl_init ();

2. Setting options
curl_setopt ($ch, Curlopt_url, "http://www.bKjia.c0m");
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_header, 0);

3. Executes and gets the returned content
$output = curl_exec ($ch);

4. Error, note that this is a Boolean value, not a null output, so it is 3 equals sign
if ($output = = = FALSE) {
echo "CURL Error:". Curl_error ($ch);
}

5. Releasing Curl Resources
Curl_close ($ch);

Source code obtained from the output
Echo $output;
?>


The second step of curl_setopt () is the most important, with a long string of curl parameters to set, which specify the details of the URL request.


Get information

This is another optional setup item that can get information about this request after Curl executes:

code as follows copy code

"!--? php
header ("Conten t-type:text/html; Charset=utf-8 ");

//1. Initialize
$ch = Curl_init ();

//2. Set options
curl_setopt ($ch, Curlopt_url, "http://www.bKjia.c0m");
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_header, 0);

//3. Execute and get HTML document contents
$output = curl_exec ($ch);

//4. Error, note that this is a Boolean value instead of a null output, so it is 3 equals sign
if ($output = = = FALSE) {
echo ' CURL Error: '. Curl_error ($ch);
}

//Get CURL information and output
$info = Curl_getinfo ($ch);
Echo ' Get '. $info [' url ']. ' Time consuming '. $info [' Total_time ']. ' seconds ';

//5. Release Curl handle
Curl_close ($ch);
?


The following information is included in the returned array:


"url"//Resource Network Address
"Content_Type"//content type and encoding
"Http_code"//HTTP status code
Size of "header_size"//Header
"Request_size"//Requested Size
"FILETIME"//File creation time
"Ssl_verify_result"//SSL verification results
"Redirect_count"//Jump Technology
"Total_time"//Total time-consuming
"Namelookup_time"//DNS query time consuming
"Connect_time"//Waiting for connection time
"Pretransfer_time"//Pre-transmission preparation time
"Size_upload"//size of uploaded data
Size of "size_download"//Download Data
"Speed_download"//download speed
"Speed_upload"//upload speed
"Download_content_length"//length of downloaded content
"Upload_content_length"//Length of uploaded content
"Starttransfer_time"//Start transfer time
"Redirect_time"//redirect time-consuming

Send data using the Post method

New from.php

The code is as follows Copy Code


Header ("content-type:text/html; Charset=utf-8 ");

Data to post
$post _data = Array (
"Hyh" = "man",
"XLP" = "Woman",
"Love" = "yes"
);

1. Initialization
$ch = Curl_init ();

2. Setting options
curl_setopt ($ch, Curlopt_url, "http://localhost/to.php");
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_post, 1); This is set to post mode
curl_setopt ($ch, Curlopt_postfields, $post _data); Add data ready to post

3. Execute and get the return content
$output = curl_exec ($ch);

4. Error, note that this is a Boolean value, not a null output, so it is 3 equals sign
if ($output = = = FALSE) {
echo "CURL Error:". Curl_error ($ch);
}

5. Releasing the curl handle
Curl_close ($ch);

Output content
Echo $output;
?>


New to.php

The code is as follows Copy Code


Header ("content-type:text/html; Charset=utf-8 ");

echo "from from.php post data to to.php success! The following is the data returned by to.php:

";
Print_r ($_post);
echo "

I ' m come from http://www.bKjia.c0m "
?>



File Upload

The upload file is very similar to the previous post because all file upload forms are submitted via the Post method.

New from.php

code as follows copy code


Header ("content-type:text/html; Charset=utf-8 ");

Data to post
$post _data = Array (
"Hyh" = "man",
"Upload" = "@c:/test.zip"//local file address to be uploaded
);

1. Initialization
$ch = Curl_init ();

2. Setting options
curl_setopt ($ch, Curlopt_url, "http://localhost/to.php");
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_post, 1); This is set to post mode
curl_setopt ($ch, Curlopt_postfields, $post _data); Add data ready to post

3. Execute and get the return content
$output = curl_exec ($ch);

4. Error, note that this is a Boolean value, not a null output, so it is 3 equals sign
if ($output = = = FALSE) {
echo "CURL Error:". Curl_error ($ch);
}

5. Releasing Curl Resources
Curl_close ($ch);

Output content
Echo $output;
?>


New to.php:

The code is as follows Copy Code


Header ("content-type:text/html; Charset=utf-8 ");

Print_r ($_files);
?>


If you need to upload a file, just pass the file path like a post variable, but remember to precede it with the @ sign.

Another useful example of curl

HTTP Authentication

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

The code is as follows Copy Code

Header ("content-type:text/html; Charset=utf-8 ");

1. Initialization
$ch = Curl_init ();

2. Setting options
curl_setopt ($ch, Curlopt_url, "http://www.bKjia.c0m");
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_userpwd, "Myusername:mypassword"); Send user name and password
curl_setopt ($ch, curlopt_followlocation, 1); You can allow it to redirect
curl_setopt ($ch, Curlopt_unrestricted_auth, 1); Allows CURL to send a user name and password after redirection

3. Execute and get the return content
$output = curl_exec ($ch);

4. Error, note that this is a Boolean value, not a null output, so it is 3 equals sign
if ($output = = = FALSE) {
echo "CURL Error:". Curl_error ($ch);
}

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


FTP upload

PHP comes with the FTP class library, but you can also use curl, you can also refer to this article: PHP using Curl to implement FTP upload

code as follows copy code

Header ("content-type:text/html; Charset=utf-8 ");

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

1. Initialization
$ch = Curl_init ();

2. Setting options
curl_setopt ($ch, Curlopt_url, "ftp://username:password@3aj.cn:21/path/to/new/file");
curl_setopt ($ch, Curlopt_returntransfer, 1);
Upload the relevant options
curl_setopt ($ch, curlopt_upload, 1);
curl_setopt ($ch, Curlopt_infile, $fp);
curl_setopt ($ch, Curlopt_infilesize, FileSize ("/path/to/file"));
Whether to turn on ASCII mode (useful when uploading text files)
curl_setopt ($ch, CURLOPT_FTPASCII, 1);

3. Execute and get the return content
$output = curl_exec ($ch);

4. Error, note that this is a Boolean value, not a null output, so it is 3 equals sign
if ($output = = = FALSE) {
echo "CURL Error:". Curl_error ($ch);
}

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


You can use a proxy to initiate a curl request:

The code is as follows Copy Code

Header ("content-type:text/html; Charset=utf-8 ");

1. Initialization
$ch = Curl_init ();

2. Setting options
curl_setopt ($ch, Curlopt_url, "http://www.bKjia.c0m");
curl_setopt ($ch, Curlopt_returntransfer, 1);
curl_setopt ($ch, Curlopt_proxy, ' 11.11.11.11:8080 '); Specify proxy Address
curl_setopt ($ch, curlopt_proxyuserpwd, ' user:pass '); Provide a user name and password, if needed

3. Execute and get the return content
$output = curl_exec ($ch);

4. Error, note that this is a Boolean value, not a null output, so it is 3 equals sign
if ($output = = = FALSE) {
echo "CURL Error:". Curl_error ($ch);
}

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


callback function


allows curl to invoke a specified callback function during a URL request. For example, start using the data as soon as the content or response is downloaded, instead of waiting for the full download to complete.

code as follows copy code

"!--? php
header ("Conten t-type:text/html; Charset=utf-8 ");

//1. Initialize
$ch = Curl_init ();

//2. Set options
curl_setopt ($ch, Curlopt_url, "http://www.bKjia.c0m");
curl_setopt ($ch, Curlopt_writefunction, "progress_function");

//3. Execute and get the return content
Curl_exec ($ch);

//4. Error, note that this is a Boolean value instead of a null output, so it is 3 equals sign
if ($output = = = FALSE) {
echo ' CURL Error: '. Curl_error ($ch);
}

//5. Release 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, in the process of receiving a URL response, as long as the receipt of a packet, the function will be called.

For a half day, let's have another high-level utility. Curl for FTP uploads

Upload limits for Web servers:

PHP default upload limit is 2M, if you want to upload more than 2M files, you must modify your PHP configuration or use the following code to build a. htaceess file.

The code is as follows Copy Code

Php_value upload_max_filesize 16M
Php_value post_max_size 20M


The maximum file upload limit is set to 20M for 16m,post_max_size because it is possible to upload a file and we also need the value of the other table items in the Post form.
Build the. htaccess to be placed in the same directory as your upload script.

Using CURL for file uploads

CURL is a tool that uses URL syntax to transfer files and data, and supports a wide variety of protocols such as HTTP, FTP, Telnet, and so on. It can accomplish many difficult tasks such as handling coockies, validating, form submission, file uploading, FTP uploading and so on.

Here, we are going to upload a file to the FTP space by using a Web form, where the FTP space is password protected.

The code is as follows Copy Code

This form page is simple, just has a file upload function.
Then we need the following PHP code to receive the uploaded files, using CURL to open a file stream and transfer to the remote FTP server.

The code is as follows Copy Code
< p>
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 chooses and uploads a file, the file is saved on the Web server first, we use fopen to open the temporary file and initial a curl session, in the sent URL, the FTP account and password to fill, and then set the other parameters of curl, you can. If the number of errors returned is 0, then the file is uploaded successfully.


Summary

Today we learned the power and flexibility of the Curl Library from: 3a Tutorial Web

http://www.bkjia.com/PHPjc/628616.html www.bkjia.com true http://www.bkjia.com/PHPjc/628616.html techarticle in PHP, the Curl function has a set of related functions, it is a very good function, we often use it to imitate a variety of login and collection work, let me give you the introduction of the Curl function ...

  • 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.