curl傳輸與擷取功能
什麼是curl?
curl是一個利用URL文法在指令行方式下工作的檔案傳輸工具。它支援很多協定:FTP,FTPS,HTTP,HTTPS,GOPHER,TELNET,DICT,FILE以及LDAP。
curl同樣支援HTTPS認證,HTTP POST方法,HTTP PUT方法,FTP上傳,HTTP上傳,代理伺服器,cookies,使用者名/密碼認證,下載下傳檔案斷點續傳等等。
PHP中常用都實作哪些功能:
1.實作遠端擷取和采集内容
2.實作PHP網頁版的FTP上傳下載下傳
3.實作模拟登陸
4.實作接口對接(API),資料傳輸等
5.實作模拟Cookie等
預設情況下PHP是不支援CURL功能的,需要在PHP.ini中開啟該功能;extension=php_curl.dll
PHP CURL 和 file_get_content()對比
代碼中使用file_get_content() 去擷取URL内容 有2點問題
1。使用file_get_content() 會很耗時 因為他每次請求都會重新對DNS查詢并不對DNS進行緩存,這樣就導緻每次請求很耗時經常伺服器請求逾時
2。如果請求的url帶有header或者其他參數 file_get_content 就比較難去處理
參考網站: http://www.jb51.net/article/57238.htm
--------------------------------------------------------------------------------------------------------------------------------------------------
curl01.php:
<?php
//簡單示例:使用curl擷取遠端網頁資料
//功能類似file_get_content
$curl = curl_init(); //初始化curl對象
$request_url = 'http://192.168.11.113:8080/upload/upload4/curl.txt';
//$request_url = 'http://www.php100.com'; //設定需要抓取的URL
curl_setopt($curl,CURLOPT_URL,$request_url);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,0);//設定curl參數,要求結果儲存到字元串中還是輸出到螢幕上
$reponse = curl_exec($curl);//運作curl,請求網頁
curl_close($curl);//關閉URL請求
?>
--------------------------------------------------------------------------------------------------------------------------------------------------
curl02.php:
<?php
//簡單示例:使用curl的post傳輸資料
$user = 'admin';
$pass = '123456';
$curlPost = 'user='.$user.'&pass='.$pass;
$ch = curl_init();
$request_url = 'localhost:8080/upload/upload4/curl_post_param.php';
curl_setopt($ch,CURLOPT_URL,$request_url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,0);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$curlPost);
$response = curl_exec($ch);
curl_close($ch);
?>
curl_post_param.php
<?php
//響應curl02.php請求,并輸出資料
if($_POST){
echo $_POST['user'].'-----'.$_POST['pass'].'<br/>';
}
?>
--------------------------------------------------------------------------------------------------------------------------------------------------
curl03.php:
//示例:使用curl模拟登陸
//tempnam()函數建立一個具有唯一檔案名的臨時檔案
//若成功,則該函數傳回新的臨時檔案名。若失敗,在傳回false
//相當于fopen->fwrite->fclose
//使用curl程式登入與直接使用浏覽器登入并不沖突,他們是互相獨立
//登陸并生成臨時檔案
$login_url = 'http://bbs.php100.com/login.php';
$post_fields = 'cktime=3600&step=2&pwuser=蔡傑&pwpwd=1991abc123';
$cookie_file = tempnam('./temp','cookie'); //C:\Windows\temp\
$ch = curl_init($login_url);
$options = array(
CURLOPT_HEADER=>0,
CURLOPT_RETURNTRANSFER=>1,
CURLOPT_POST=>1,
CURLOPT_COOKIEJAR=>$cookie_file,
CURLOPT_POSTFIELDS=>$post_fields,
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
curl_close($ch);
//登陸後的頁面
$url = 'http://bbs.php100.com/index.php';
$ch = curl_init($url);
$options = array(
CURLOPT_HEADER=>0,
CURLOPT_RETURNTRANSFER=>0,
CURLOPT_COOKIEFILE=>$cookie_file,
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
curl_close($ch);
//可以使用正規表達式采集傳回的結果
//preg_match('/<li>金錢:(.*)</li>/',$response,$arr);echo $arr[1];
參考:
http://www.csdn123.com/html/topnews201408/60/2660.htm