php使用curl代理
使用php 的curl 庫可以簡單和有效地去抓網頁。你只需要運行一個腳本,然後分析一下你所抓取的網頁,然後就可以以程序的方式得到你想要的數據了。無論是你想從從一個鏈接上取部分數據,或是取一個xml 文件並把其導入數據庫,那怕就是簡單的獲取網頁內容,curl 是一個功能強大的php 庫。本文主要講述如果使用這個php 庫。
啟用 curl 設置
首先,我們得先要確定我們的php 是否開啟了這個庫,你可以通過使用php_info() 函數來得到這一信息。
php代碼
﹤?php
phpinfo();
?﹥
如果你可以在網頁上看到下面的輸出,那麽表示curl 庫已被開啟。
如果你看到的話,那麽你需要設置你的php 並開啟這個庫。如果你是在windows 平臺下,那麽非常簡單,你需要改一改你的php.ini 文件的設置,找到php_curl.dll ,並取消前面的分號註釋就行了。如下所示:
php代碼
//取消下在的註釋
extension=php_curl.dll
如果你是在linux 下面,那麽,你需要重新編譯你的php 了,編輯時,你需要打開編譯參數—— 在configure 命令上加上“–with-curl” 參數。
一個小示例
如果一切就緒,下面是一個小例程:
php代碼
﹤?php
// 初始化一個 curl 對象
$curl = curl_init();
// 設置你需要抓取的url
curl_setopt($curl, curlopt_url, 'http://cocre.com');
// 設置header
curl_setopt($curl, curlopt_header, 1);
// 設置curl 參數,要求結果保存到字符串中還是輸出到屏幕上。
curl_setopt($curl, curlopt_returntransfer, 1);
// 運行curl,請求網頁
$data = curl_exec($curl);
// 關閉url請求
curl_close($curl);
// 顯示獲得的數據
var_dump($data);
如何post 數據
上面是抓取網頁的代碼,下面則是向某個網頁post 數據。假設我們有一個處理表單的網址http://www.example.com/sendsms.php ,其可以接受兩個表單域,一個是電話號碼,一個是短信內容。
php代碼
﹤?php
$phonenumber = '13912345678';
$message = 'this message was generated by curl and php';
$curlpost = 'pnumber=' . urlencode($phonenumber) . '&message=' . urlencode($message) . '&submit=send';
$ch = curl_init();
curl_setopt($ch, curlopt_url, 'http://www.example.com/sendsms.php');
curl_setopt($ch, curlopt_header, 1);
curl_setopt($ch, curlopt_returntransfer, 1);
curl_setopt($ch, curlopt_post, 1);
curl_setopt($ch, curlopt_postfields, $curlpost);
$data = curl_exec();
curl_close($ch);
?﹥
從上面的程序我們可以看到,使用curlopt_post 設置http 協議的post 方法,而不是get 方法,然後以curlopt_postfields 設置post 的數據。
關於代理服務器
下面是一個如何使用代理服務器的示例。請註意其中高亮的代碼,代碼很簡單,我就不用多說了。
php代碼
﹤?php
$ch = curl_init();
curl_setopt($ch, curlopt_url, 'http://www.example.com');
curl_setopt($ch, curlopt_header, 1);
curl_setopt($ch, curlopt_returntransfer, 1);
curl_setopt($ch, curlopt_httpproxytunnel, 1);
curl_setopt($ch, curlopt_proxy, 'fakeproxy.com:1080');
curl_setopt($ch, curlopt_proxyuserpwd, 'user:password');
$data = curl_exec();
curl_close($ch);
?﹥
關於ssl 和cookie
關於ssl 也就是https 協議,你只需要把curlopt_url 連接中的http:// 變成https:// 就可以了。當然,還有一個參數叫curlopt_ssl_verifyhost 可以設置為驗證站點。
關於cookie ,你需要了解下面三個參數:
curlopt_cookie ,在當面的會話中設置一個cookie
curlopt_cookiejar ,當會話結束的時候保存一個cookie
curlopt_cookiefile ,cookie 的文件。
http 服務器認證
最後,我們來看一看http 服務器認證的情況。
php代碼
﹤?php
$ch = curl_init();
curl_setopt($ch, curlopt_url, 'http://www.example.com');
curl_setopt($ch, curlopt_returntransfer, 1);
curl_setopt($ch, curlopt_httpauth, curlauth_basic);
curl_setopt(curlopt_userpwd, '[username]:[password]')
$data = curl_exec();
curl_close($ch);
?﹥
总结,curl关于http可以做三件事:
1,直接抓取某个地址的网页。
2,向某个地址post数据。
3,经过代理访问某个网页。也可以post。
其他,还有https和cookie。
關於其它更多的內容,請參看相關的curl 手冊。
