PHP-based cURL Quick Start 1

Source: Internet
Author: User
PHP-based cURL quick start 1cURL is a tool that uses URL syntax to transmit files and data. it supports many protocols, such as HTTP, FTP, and TELNET. The best thing is that PHP also supports the cURL Library. This article describes some advanced features of cURL and how to use it in PHP. Why use cU-based PHP cURL Quick Start 1

CURL is a tool that uses URL syntax to transmit files and data. it supports many protocols, such as HTTP, FTP, and TELNET. The best thing is that PHP also supports the cURL Library. This article describes some advanced features of cURL and how to use it in PHP.

Why use cURL?

Yes. we can use other methods to obtain the webpage content. Most of the time, I want to be lazy and use simple PHP functions directly:


Reference content is as follows:

$content = file_get_contents("http://www.nettuts.com");// or$lines = file("http://www.nettuts.com");// orreadfile(http://www.nettuts.com);
?



However, this approach lacks flexibility and effective error handling. Moreover, you cannot use it to complete difficult tasks, such as coockies processing, verification, form submission, and file upload.

Reference:
CURL is a powerful library that supports many different protocols and options and provides URL request-related details.

Basic structure

Before learning more complex functions, let's take a look at the basic steps for creating cURL requests in PHP:
Initialization
Set variables
Execute and obtain results
Release cURL handle


Reference content is as follows:

// 1. initialize $ ch = curl_init (); // 2. set options, including URLcurl_setopt ($ ch, CURLOPT_URL, "http://www.nettuts.com"); 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. release curl handle curl_close ($ ch );
?


The second step (that is, curl_setopt () is the most important, and all the mysteries are here. There is a long string of cURL parameters that can be set. they can specify the details of URL requests. It may be difficult to read and understand all at once, so today we will only try out the more common and useful options.

Check error

You can add a statement to check for errors (although this is not required ):


Reference content is as follows:

// ...$output = curl_exec($ch);if ($output === FALSE) {echo "cURL Error: " . curl_error($ch);}// ...
?



Note that we use "= FALSE" instead of "= FALSE" for comparison ". Because we need to distinguish between null output and boolean value FALSE, the latter is a real error.

?

Obtain information

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


Reference content is as follows:

//... Curl_exec ($ ch); $ info = curl_getinfo ($ ch); echo 'get '. $ info ['URL']. 'consumed time '. $ info ['total _ time']. 'second ';//...
?



The returned array contains the following information:
"Url" // resource network address
"Content_type" // content 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" // The 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

Browser-based redirection

In the first example, we will provide a piece of code to detect whether the server has browser-based redirection. For example, some websites redirect webpages based on whether the browser is a mobile phone or even the country from which the user is from.

We use the CURLOPT_HTTPHEADER option to set the HTTP request header (http headers) that we send, including the user agent information and the default language. Then let's see if these websites will redirect us to different URLs.

Reference content is as follows:

// URL $ urls = array (" http://www.cnn.com "," http://www.mozilla.com "," http://www.facebook.com "); // Browser information for testing $ browsers = array (" standard "=> array (" user_agent "=>" Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv: 1.9.1.6) Gecko/20091201 Firefox/3.5.6 (. net clr 3.5.30729) "," language "=>" en-us, en; q = 0.5 "), "iphone" => array ("user_agent" => "Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420 + (KHTML, like Gecko) version/3.0 Mobile/1A537a Safari/419.3 "," language "=>" en ")," french "=> Array (" user_agent "=>" Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; GTB6 ;. net clr 2.0.50727) "," language "=>" fr, fr-FR; q = 0.5 "); foreach ($ urls as $ url) {echo" URL: $ url \ n "; foreach ($ browsers as $ test_name => $ browser) {$ ch = curl_init (); // Set urlcurl_setopt ($ ch, CURLOPT_URL, $ url ); // Set the browser's specific headercurl_setopt ($ ch, CURLOPT_HTTPHEADER, array ("User-Agent: {$ browser ['User _ agent']}", "Accept -Language: {$ browser ['language']} "); // You do not need curl_setopt ($ ch, CURLOPT_NOBODY, 1) for the page content ); // return HTTP headercurl_setopt ($ ch, CURLOPT_HEADER, 1); // return the result instead of curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 ); $ output = curl_exec ($ ch); curl_close ($ ch); // is there any redirected HTTP header information? If (preg_match ("! Location :(.*)! ", $ Output, $ matches) {echo" $ test_name: redirects to $ matches [1] \ n ";} else {echo" $ test_name: no redirection \ n ";}} echo" \ n ";}
?


First, we create a set of URLs to be tested, and then specify a set of browser information to be tested. Finally, the possible situation of URL matching and browser matching is tested cyclically.

Because the cURL option is specified, only the HTTP header information (stored in $ output) is returned ). Using a simple regular expression, we can check whether the header information contains the "Location.

The following results should be returned when you run this code:




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.