


cURL quick start tutorial based on PHP (thief collection program)_PHP tutorial
Jul 21, 2016 pm 03:29 PM最爽的是,PHP也支持 cURL 庫。本文將介紹 cURL 的一些高級特性,以及在PHP中如何運用它。
為什么要用 cURL?
是的,我們可以通過其他辦法獲取網頁內容。大多數時候,我因為想偷懶,都直接用簡單的PHP函數:
$content = file_get_contents("http://www.jb51.net");
// or
$lines = file("http://www.jb51.net");
// or
readfile(http://www.jb51.net);
不過,這種做法缺乏靈活性和有效的錯誤處理。而且,你也不能用它完成一些高難度任務——比如處理coockies、驗證、表單提交、文件上傳等等。
引用:
cURL 是一種功能強大的庫,支持很多不同的協(xié)議、選項,能提供 URL 請求相關的各種細節(jié)信息。
基本結構
在學習更為復雜的功能之前,先來看一下在PHP中建立cURL請求的基本步驟:
- 初始化
- 設置變量
- 執(zhí)行并獲取結果
- 釋放cURL句柄
// 1. 初始化
$ch = curl_init();
// 2. 設置選項,包括URL
curl_setopt($ch, CURLOPT_URL, "http://www.jb51.net");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
// 3. 執(zhí)行并獲取HTML文檔內容
$output = curl_exec($ch);
// 4. 釋放curl句柄
curl_close($ch);
第二步(也就是 curl_setopt() )最為重要,一切玄妙均在此。有一長串cURL參數可供設置,它們能指定URL請求的各個細節(jié)。要一次性全部看完并理解可能比較困難,所以今天我們只試一下那些更常用也更有用的選項。
檢查錯誤
你可以加一段檢查錯誤的語句(雖然這并不是必需的):
// ...
$output = curl_exec($ch);
if ($output === FALSE) {
??? echo "cURL Error: " . curl_error($ch);
}
// ...
請注意,比較的時候我們用的是“=== FALSE”,而非“== FALSE”。因為我們得區(qū)分 空輸出 和 布爾值FALSE,后者才是真正的錯誤。
獲取信息
這是另一個可選的設置項,能夠在cURL執(zhí)行后獲取這一請求的有關信息:
// ...
curl_exec($ch);
$info = curl_getinfo($ch);
echo '獲取'. $info['url'] . '耗時'. $info['total_time'] . '秒';
// ...
返回的數組中包括了以下信息:
- “url” //資源網絡地址
- “content_type” //內容編碼
- “http_code” //HTTP狀態(tài)碼
- “header_size” //header的大小
- “request_size” //請求的大小
- “filetime” //文件創(chuàng)建時間
- “ssl_verify_result” //SSL驗證結果
- “redirect_count” //跳轉技術??
- “total_time” //總耗時
- “namelookup_time” //DNS查詢耗時
- “connect_time” //等待連接耗時
- “pretransfer_time” //傳輸前準備耗時
- “size_upload” //上傳數據的大小
- “size_download” //下載數據的大小
- “speed_download” //下載速度
- “speed_upload” //上傳速度
- “download_content_length”//下載內容的長度
- “upload_content_length” //上傳內容的長度??
- “starttransfer_time” //開始傳輸的時間
- “redirect_time”//重定向耗時
基于瀏覽器的重定向
在第一個例子中,我們將提供一段用于偵測服務器是否有基于瀏覽器的重定向的代碼。例如,有些網站會根據是否是手機瀏覽器甚至用戶來自哪個國家來重定向網頁。
我們利用 CURLOPT_HTTPHEADER 選項來設定我們發(fā)送出的HTTP請求頭信息(http headers),包括user agent信息和默認語言。然后我們來看看這些特定網站是否會把我們重定向到不同的URL。
// 測試用的URL |
首先,我們建立一組需要測試的URL,接著指定一組需要測試的瀏覽器信息。最后通過循環(huán)測試各種URL和瀏覽器匹配可能產生的情況。
因為我們指定了cURL選項,所以返回的輸出內容則只包括HTTP頭信息(被存放于 $output 中)。利用一個簡單的正則,我們檢查這個頭信息中是否包含了“Location:”字樣。
運行這段代碼應該會返回如下結果:
用POST方法發(fā)送數據
當發(fā)起GET請求時,數據可以通過“查詢字串”(query string)傳遞給一個URL。例如,在google中搜索時,搜索關鍵即為URL的查詢字串的一部分:
http://www.google.com/search?q=nettuts
這種情況下你可能并不需要cURL來模擬。把這個URL丟給“file_get_contents()”就能得到相同結果。
不過有一些HTML表單是用POST方法提交的。這種表單提交時,數據是通過 HTTP請求體(request body) 發(fā)送,而不是查詢字串。例如,當使用CodeIgniter論壇的表單,無論你輸入什么關鍵字,總是被POST到如下頁面:
http://codeigniter.com/forums/do_search/
你可以用PHP腳本來模擬這種URL請求。首先,新建一個可以接受并顯示POST數據的文件,我們給它命名為post_output.php:
print_r($_POST);
接下來,寫一段PHP腳本來執(zhí)行cURL請求:
$url = "http://localhost/post_output.php"; |
執(zhí)行代碼后應該會得到以下結果:
這段腳本發(fā)送一個POST請求給 post_output.php ,這個頁面 $_POST 變量并返回,我們利用cURL捕捉了這個輸出。
文件上傳
上傳文件和前面的POST十分相似。因為所有的文件上傳表單都是通過POST方法提交的。
首先新建一個接收文件的頁面,命名為 upload_output.php:
print_r($_FILES);
以下是真正執(zhí)行文件上傳任務的腳本:
$url = "http://localhost/upload_output.php"; |
如果你需要上傳一個文件,只需要把文件路徑像一個post變量一樣傳過去,不過記得在前面加上@符號。執(zhí)行這段腳本應該會得到如下輸出:
cURL批處理(multi cURL)
cURL還有一個高級特性——批處理句柄(handle)。這一特性允許你同時或異步地打開多個URL連接。
下面是來自來自php.net的示例代碼:
// 創(chuàng)建兩個cURL資源 |
這里要做的就是打開多個cURL句柄并指派給一個批處理句柄。然后你就只需在一個while循環(huán)里等它執(zhí)行完畢。
這個示例中有兩個主要循環(huán)。第一個 do-while 循環(huán)重復調用 curl_multi_exec() 。這個函數是無隔斷(non-blocking)的,但會盡可能少地執(zhí)行。它返回一個狀態(tài)值,只要這個值等于常量 CURLM_CALL_MULTI_PERFORM ,就代表還有一些刻不容緩的工作要做(例如,把對應URL的http頭信息發(fā)送出去)。也就是說,我們需要不斷調用該函數,直到返回值發(fā)生改變。
而接下來的 while 循環(huán),只在 $active 變量為 true 時繼續(xù)。這一變量之前作為第二個參數傳給了 curl_multi_exec() ,代表只要批處理句柄中是否還有活動連接。接著,我們調用 curl_multi_select() ,在活動連接(例如接受服務器響應)出現(xiàn)之前,它都是被“屏蔽”的。這個函數成功執(zhí)行后,我們又會進入另一個 do-while 循環(huán),繼續(xù)下一條URL。
還是來看一看怎么把這一功能用到實處吧:
WordPress 連接檢查器
想象一下你有一個文章數目龐大的博客,這些文章中包含了大量外部網站鏈接。一段時間之后,因為這樣那樣的原因,這些鏈接中相當數量都失效了。要么是被和諧了,要么是整個站點都被功夫網了...
我們下面建立一個腳本,分析所有這些鏈接,找出打不開或者404的網站/網頁,并生成一個報告。
請注意,以下并不是一個真正可用的WordPress插件,僅僅是一段獨立功能的腳本而已,僅供演示,謝謝。
好,開始吧。首先,從數據庫中讀取所有這些鏈接:
// CONFIG |
我們首先配置好數據庫,一系列要排除的域名($excluded_domains),以及最大并發(fā)連接數($max_connections)。然后,連接數據庫,獲取文章和包含的鏈接,把它們收集到一個數組中($url_list)。
下面的代碼有點復雜了,因此我將一小步一小步地詳細解釋:
// 1. Batch processor |
下面解釋一下以上代碼。列表的序號對應著代碼注釋中的順序數字。
- 新建一個批處理器。Created a multi handle.
- 稍后我們將創(chuàng)建一個把URL加入批處理器的函數 add_url_to_multi_handle() 。每當這個函數被調用,就有一個新url被加入批處理器。一開始,我們給批處理器添加了10個URL(這一數字由 $max_connections 所決定)。
- 運行 curl_multi_exec() 進行初始化工作是必須的,只要它返回 CURLM_CALL_MULTI_PERFORM 就還有事情要做。這么做主要是為了創(chuàng)建連接,它不會等待完整的URL響應。
- 只要批處理中還有活動連接主循環(huán)就會一直持續(xù)。
- curl_multi_select() 會一直等待,直到某個URL查詢產生活動連接。
- cURL的活兒又來了,主要是獲取響應數據。
- 檢查各種信息。當一個URL請求完成時,會返回一個數組。
- 在返回的數組中有一個 cURL 句柄。我們利用其獲取單個cURL請求的相應信息。
- 如果這是一個死鏈或者請求超時,不會返回http狀態(tài)碼。
- 如果這個頁面找不到了,會返回404狀態(tài)碼。
- 其他情況我們都認為這個鏈接是可用的(當然,你也可以再檢查一下500錯誤之類...)。
- 從該批次移除這個cURL句柄,因為它已經沒有利用價值了,關了它!
- 很好,現(xiàn)在可以另外加一個URL進來了。再一次地,初始化工作又開始進行...
- 嗯,該干的都干了。關閉批處理器,生成報告。
- 回過頭來看給批處理器添加新URL的函數。這個函數每調用一次,靜態(tài)變量 $index 就遞增一次,這樣我們才能知道還剩多少URL沒處理。
我把這個腳本在我的博客上跑了一遍(測試需要,有一些錯誤鏈接是故意加上的),結果如下:
|
共檢查約40個URL,只耗費兩秒不到。當需要檢查更加大量的URL時,其省心省力的效果可想而知!如果你同時打開10個連接,還能再快上10倍!另外,你還可以利用cURL批處理的無隔斷特性來處理大量URL請求,而不會阻塞你的Web腳本。
另一些有用的cURL 選項
HTTP 認證
如果某個URL請求需要基于 HTTP 的身份驗證,你可以使用下面的代碼:
復制內容到剪貼板代碼:
$url = "http://www.somesite.com/members/"; |
FTP 上傳
PHP 自帶有 FTP 類庫, 但你也能用 cURL:
// 開一個文件指針 |
The art of circumventing the wall
You can use a proxy to make cURL requests:
$ch = curl_init();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 指定代理地址
curl_setopt($ch, CURLOPT_PROXY, '11.11.11.11:8080');
// 如果需要的話,提供用戶名和密碼
curl_setopt($ch, CURLOPT_PROXYUSERPWD,'user:pass');
$output = curl_exec($ch);
curl_close ($ch);
curl_setopt($ch, CURLOPT_URL,'http://www.example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//Specify the proxy address
curl_setopt($ch, CURLOPT_PROXY, '11.11.11.11:8080');
// Provide username and password if necessary
curl_setopt($ch, CURLOPT_PROXYUSERPWD,' user:pass');
$output = curl_exec($ch);
curl_close ($ch);
Callback function
You can let cURL call a specified callback function during a URL request. For example, start utilizing data as soon as the content or response is downloading, rather than waiting until it is completely downloaded. $ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://net.tutsplus.com');
curl_setopt($ch, CURLOPT_WRITEFUNCTION,"progress_function");
curl_exec($ch);
curl_close ($ch);
function progress_function($ch,$str) {
??? echo $str;
??? return strlen($str);
}
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL,'http://net.tutsplus.com'); curl_setopt($ch, CURLOPT_WRITEFUNCTION,"progress_function") ; curl_exec($ch); curl_close ($ch); 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 process of receiving the URL response, this function will be called as long as a data packet is received.
SummaryToday we learned together the powerful functions and flexible scalability of the
cURLlibrary. Hope you like it. The next time you want to make a URL request, consider cURL!
Original text: Quick Start with cURL based on PHPhttp: //www.bkjia.com/PHPjc/323415.htmlTechArticleThe best thing is that PHP also supports the cURL library. This article will introduce some advanced features of cURL and how to use it in PHP. Why use cURL? Yes, we can get it through other methods...

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.
