另一些有用的cURL 選項
HTTP 認證
如果某個URL請求需要基於 HTTP 的身份驗證,你可以使用下面的代碼:
複製內容到剪貼板代碼:
以下爲引用的內容:
$url = "http://www.somesite.com/members/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 發送用戶名和密碼
curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword");
// 你可以允許其重定向
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// 下面的選項讓 cURL 在重定向後
// 也能發送用戶名和密碼
curl_setopt($ch, CURLOPT_UNRESTRICTED_AUTH, 1);
$output = curl_exec($ch);
curl_close($ch);
|
FTP 上傳
PHP 自帶有 FTP 類庫, 但你也能用 cURL:
以下爲引用的內容:
// 開一個文件指針
$file = fopen("/path/to/file", "r");
// url裏包含了大部分所需信息
$url = "ftp://username:[email protected]:21/path/to/new/file";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 上傳相關的選項
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize("/path/to/file"));
// 是否開啓ASCII模式 (上傳文本文件時有用)
curl_setopt($ch, CURLOPT_FTPASCII, 1);
$output = curl_exec($ch);
curl_close($ch);
|
翻牆術
你可以用代理髮起cURL請求:
以下爲引用的內容:
$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);
|
回調函數
可以在一個URL請求過程中,讓cURL調用某指定的回調函數。例如,在內容或者響應下載的過程中立刻開始利用數據,而不用等到完全下載完。
以下爲引用的內容:
$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);
}
|
這個回調函數必須返回字串的長度,不然此功能將無法正常使用。
在URL響應接收的過程中,只要收到一個數據包,這個函數就會被調用。
小結
今天我們一起學習了cURL庫的強大功能和靈活的擴展性。希望你喜歡。下一次要發起URL請求時,考慮下cURL吧!
原文:基於PHP的cURL快速入門
英文原文:http://net.tutsplus.com/tutorial%20...%20for-mastering-curl/
原文作者:Burak Guzel
本文鏈接:http://www.blueidea.com/tech/program/2010/7348.asp