header('content-type:text/html;charset=utf-8');
<pre name="code" class="html">function curlPost($url,$data,$method){
$ch = curl_init(); //1.初始化
curl_setopt($ch, CURLOPT_URL, $url); //2.請求位址
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);//3.請求方式
//4.參數如下
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//https
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');//模拟浏覽器
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Accept-Encoding: gzip, deflate'));//gzip解壓内容
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
if($method=="POST"){//5.post方式的時候添加資料
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$tmpInfo = curl_exec($ch);//6.執行
if (curl_errno($ch)) {//7.如果出錯
return curl_error($ch);
}
curl_close($ch);//8.關閉
return $tmpInfo;
}
$data=array('name' => '1234');
$url="http://www.sohu.com/";
$method="GET";
$file=curlPost($url,$data,$method);
$file=mb_convert_encoding($file,'UTF-8','GBK');
echo $file;
當cookie認證登陸的時候
<?php
$cookie_file = tempnam('./temp','cookie');
function weixinPost($url,$data,$method,$setcooke=false,$cookie_file=false){
$ch = curl_init(); //1.初始化
curl_setopt($ch, CURLOPT_URL, $url); //2.請求位址
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);//3.請求方式
//4.參數如下
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
if($method=="POST"){//5.post方式的時候添加資料
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
if($setcooke==true){
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
}else{
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$tmpInfo = curl_exec($ch);//6.執行
if (curl_errno($ch)) {//7.如果出錯
return curl_error($ch);
}
curl_close($ch);//8.關閉
return $tmpInfo;
}
$data=array('username' => '***','password'=>'***');
$url="http://www.xinxinj.com/login.php";
$method="POST";
$file=weixinPost($url,$data,$method,true,$cookie_file);
echo $file;
$url="http://www.xinxinj.com/admin.php";
$method="GET";
$file=weixinPost($url,$data,$method,false,$cookie_file);
echo $file;
?>
1.cURL介紹
cURL 是一個利用URL文法規定來傳輸檔案和資料的工具,支援很多協定,如HTTP、FTP、TELNET等。最爽的是,PHP也支援 cURL 庫。本文将介紹 cURL 的一些進階特性,以及在PHP中如何運用它。簡單來說,curl就是抓取頁面的更新版,即支援GET、POST等浏覽器行為,進而可以達到一個模拟浏覽器操作的目的。
最簡單的一個模型就是如下圖所示的模型:

2.基本結構 在學習更為複雜的功能之前,先來看一下在PHP中建立cURL請求的基本步驟:
(1)初始化 curl_init()
(2)設定變量 curl_setopt() 。最為重要,一切玄妙均在此。有一長串cURL參數可供設定,它們能指定URL請求的各個細節。要一次性全部看完并了解可能比較困難,是以今天我們隻試一下那些更常用也更有用的選項。
(3)執行并擷取結果 curl_exec()
(4)釋放cURL句柄 curl_close()
3.cURL實作Get和Post
POST的過程比較複雜一些,但是原理和浏覽器送出過程相同,簡單來說,就是利用curl直接将使用者名和密碼(或者其他相應的參數,這個根據post頁面具體讨論)送出到post指向的處理頁面即可。過程如下圖: