国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Backend Development PHP Tutorial 基于PHP的cURL快速入門(mén)一

基于PHP的cURL快速入門(mén)一

Jun 13, 2016 pm 01:04 PM
curl http url

基于PHP的cURL快速入門(mén)1

cURL 是一個(gè)利用URL語(yǔ)法規(guī)定來(lái)傳輸文件和數(shù)據(jù)的工具,支持很多協(xié)議,如HTTP、FTP、TELNET等。最爽的是,PHP也支持 cURL 庫(kù)。本文將介紹 cURL 的一些高級(jí)特性,以及在PHP中如何運(yùn)用它。

為什么要用 cURL?

是的,我們可以通過(guò)其他辦法獲取網(wǎng)頁(yè)內(nèi)容。大多數(shù)時(shí)候,我因?yàn)橄胪祽校贾苯佑煤?jiǎn)單的PHP函數(shù):


以下為引用的內(nèi)容:

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



不過(guò),這種做法缺乏靈活性和有效的錯(cuò)誤處理。而且,你也不能用它完成一些高難度任務(wù)――比如處理coockies、驗(yàn)證、表單提交、文件上傳等等。

引用:
cURL 是一種功能強(qiáng)大的庫(kù),支持很多不同的協(xié)議、選項(xiàng),能提供 URL 請(qǐng)求相關(guān)的各種細(xì)節(jié)信息。

基本結(jié)構(gòu)

在學(xué)習(xí)更為復(fù)雜的功能之前,先來(lái)看一下在PHP中建立cURL請(qǐng)求的基本步驟:
初始化
設(shè)置變量
執(zhí)行并獲取結(jié)果
釋放cURL句柄


以下為引用的內(nèi)容:

// 1. 初始化
$ch = curl_init();
// 2. 設(shè)置選項(xiàng),包括URL
curl_setopt($ch, CURLOPT_URL, "http://www.nettuts.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// 3. 執(zhí)行并獲取HTML文檔內(nèi)容
$output = curl_exec($ch);
// 4. 釋放curl句柄
curl_close($ch);
?


第二步(也就是 curl_setopt() )最為重要,一切玄妙均在此。有一長(zhǎng)串cURL參數(shù)可供設(shè)置,它們能指定URL請(qǐng)求的各個(gè)細(xì)節(jié)。要一次性全部看完并理解可能比較困難,所以今天我們只試一下那些更常用也更有用的選項(xiàng)。

檢查錯(cuò)誤

你可以加一段檢查錯(cuò)誤的語(yǔ)句(雖然這并不是必需的):


以下為引用的內(nèi)容:

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



請(qǐng)注意,比較的時(shí)候我們用的是“=== FALSE”,而非“== FALSE”。因?yàn)槲覀兊脜^(qū)分 空輸出 和 布爾值FALSE,后者才是真正的錯(cuò)誤。

?

獲取信息

這是另一個(gè)可選的設(shè)置項(xiàng),能夠在cURL執(zhí)行后獲取這一請(qǐng)求的有關(guān)信息:


以下為引用的內(nèi)容:

// ...
curl_exec($ch);
$info = curl_getinfo($ch);
echo '獲取'. $info['url'] . '耗時(shí)'. $info['total_time'] . '秒';
// ...
?



返回的數(shù)組中包括了以下信息:
“url” //資源網(wǎng)絡(luò)地址
“content_type” //內(nèi)容編碼
“http_code” //HTTP狀態(tài)碼
“header_size” //header的大小
“request_size” //請(qǐng)求的大小
“filetime” //文件創(chuàng)建時(shí)間
“ssl_verify_result” //SSL驗(yàn)證結(jié)果
“redirect_count” //跳轉(zhuǎn)技術(shù)
“total_time” //總耗時(shí)
“namelookup_time” //DNS查詢(xún)耗時(shí)
“connect_time” //等待連接耗時(shí)
“pretransfer_time” //傳輸前準(zhǔn)備耗時(shí)
“size_upload” //上傳數(shù)據(jù)的大小
“size_download” //下載數(shù)據(jù)的大小
“speed_download” //下載速度
“speed_upload” //上傳速度
“download_content_length”//下載內(nèi)容的長(zhǎng)度
“upload_content_length” //上傳內(nèi)容的長(zhǎng)度
“starttransfer_time” //開(kāi)始傳輸?shù)臅r(shí)間
“redirect_time”//重定向耗時(shí)

基于瀏覽器的重定向

在第一個(gè)例子中,我們將提供一段用于偵測(cè)服務(wù)器是否有基于瀏覽器的重定向的代碼。例如,有些網(wǎng)站會(huì)根據(jù)是否是手機(jī)瀏覽器甚至用戶(hù)來(lái)自哪個(gè)國(guó)家來(lái)重定向網(wǎng)頁(yè)。

我們利用 CURLOPT_HTTPHEADER 選項(xiàng)來(lái)設(shè)定我們發(fā)送出的HTTP請(qǐng)求頭信息(http headers),包括user agent信息和默認(rèn)語(yǔ)言。然后我們來(lái)看看這些特定網(wǎng)站是否會(huì)把我們重定向到不同的URL。

以下為引用的內(nèi)容:

// 測(cè)試用的URL
$urls = array(
"http://www.cnn.com",
"http://www.mozilla.com",
"http://www.facebook.com"
);
// 測(cè)試用的瀏覽器信息
$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();
// 設(shè)置 url
curl_setopt($ch, CURLOPT_URL, $url);
// 設(shè)置瀏覽器的特定header
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"User-Agent: {$browser['user_agent']}",
"Accept-Language: {$browser['language']}"
));
// 頁(yè)面內(nèi)容我們并不需要
curl_setopt($ch, CURLOPT_NOBODY, 1);
// 只需返回HTTP header
curl_setopt($ch, CURLOPT_HEADER, 1);
// 返回結(jié)果,而不是輸出它
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
// 有重定向的HTTP頭信息嗎?
if (preg_match("!Location: (.*)!", $output, $matches)) {
echo "$test_name: redirects to $matches[1]\n";
} else {
echo "$test_name: no redirection\n";
}
}
echo "\n\n";
}
?


首先,我們建立一組需要測(cè)試的URL,接著指定一組需要測(cè)試的瀏覽器信息。最后通過(guò)循環(huán)測(cè)試各種URL和瀏覽器匹配可能產(chǎn)生的情況。

因?yàn)槲覀冎付薱URL選項(xiàng),所以返回的輸出內(nèi)容則只包括HTTP頭信息(被存放于 $output 中)。利用一個(gè)簡(jiǎn)單的正則,我們檢查這個(gè)頭信息中是否包含了“Location:”字樣。

運(yùn)行這段代碼應(yīng)該會(huì)返回如下結(jié)果:




Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
Why NameResolutionError(self.host, self, e) from e and how to solve it Why NameResolutionError(self.host, self, e) from e and how to solve it Mar 01, 2024 pm 01:20 PM

The reason for the error is NameResolutionError(self.host,self,e)frome, which is an exception type in the urllib3 library. The reason for this error is that DNS resolution failed, that is, the host name or IP address attempted to be resolved cannot be found. This may be caused by the entered URL address being incorrect or the DNS server being temporarily unavailable. How to solve this error There may be several ways to solve this error: Check whether the entered URL address is correct and make sure it is accessible Make sure the DNS server is available, you can try using the "ping" command on the command line to test whether the DNS server is available Try accessing the website using the IP address instead of the hostname if behind a proxy

What does http status code 520 mean? What does http status code 520 mean? Oct 13, 2023 pm 03:11 PM

HTTP status code 520 means that the server encountered an unknown error while processing the request and cannot provide more specific information. Used to indicate that an unknown error occurred when the server was processing the request, which may be caused by server configuration problems, network problems, or other unknown reasons. This is usually caused by server configuration issues, network issues, server overload, or coding errors. If you encounter a status code 520 error, it is best to contact the website administrator or technical support team for more information and assistance.

Tutorial on updating curl version under Linux! Tutorial on updating curl version under Linux! Mar 07, 2024 am 08:30 AM

To update the curl version under Linux, you can follow the steps below: Check the current curl version: First, you need to determine the curl version installed in the current system. Open a terminal and execute the following command: curl --version This command will display the current curl version information. Confirm available curl version: Before updating curl, you need to confirm the latest version available. You can visit curl's official website (curl.haxx.se) or related software sources to find the latest version of curl. Download the curl source code: Using curl or a browser, download the source code file for the curl version of your choice (usually .tar.gz or .tar.bz2

What is the difference between html and url What is the difference between html and url Mar 06, 2024 pm 03:06 PM

Differences: 1. Different definitions, url is a uniform resource locator, and html is a hypertext markup language; 2. There can be many urls in an html, but only one html page can exist in a url; 3. html refers to is a web page, and url refers to the website address.

What is http status code 403? What is http status code 403? Oct 07, 2023 pm 02:04 PM

HTTP status code 403 means that the server rejected the client's request. The solution to http status code 403 is: 1. Check the authentication credentials. If the server requires authentication, ensure that the correct credentials are provided; 2. Check the IP address restrictions. If the server has restricted the IP address, ensure that the client's IP address is restricted. Whitelisted or not blacklisted; 3. Check the file permission settings. If the 403 status code is related to the permission settings of the file or directory, ensure that the client has sufficient permissions to access these files or directories, etc.

Understand common application scenarios of web page redirection and understand the HTTP 301 status code Understand common application scenarios of web page redirection and understand the HTTP 301 status code Feb 18, 2024 pm 08:41 PM

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

How to handle 301 redirection of web pages in PHP Curl? How to handle 301 redirection of web pages in PHP Curl? Mar 08, 2024 am 11:36 AM

How to handle 301 redirection of web pages in PHPCurl? When using PHPCurl to send network requests, you will often encounter a 301 status code returned by the web page, indicating that the page has been permanently redirected. In order to handle this situation correctly, we need to add some specific options and processing logic to the Curl request. The following will introduce in detail how to handle 301 redirection of web pages in PHPCurl, and provide specific code examples. 301 redirect processing principle 301 redirect means that the server returns a 30

HTTP 200 OK: Understand the meaning and purpose of a successful response HTTP 200 OK: Understand the meaning and purpose of a successful response Dec 26, 2023 am 10:25 AM

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

See all articles