萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php中Curl函數常用的兩個例子

php中Curl函數常用的兩個例子

   例子, 模擬登陸

 代碼如下   /**
* 模擬登陸
* $url 請求地址
* $post 需要POST的數據
* $cookie 登陸時取的的COOKIE
* $cookiejar cookie要存到的位置 例如/tmp/test.cookie
* $referer 上頁地址
*
**/
function vcurl($url, $post = '', $cookie = '', $cookiejar = '', $referer = ''){
$tmpInfo = '';
//用來存放cookie的文件
//初始化curl
$curl = curl_init();
//設定目標網址
curl_setopt($curl, CURLOPT_URL, $url);
//使用目前所用的浏覽器代理
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
//如果有Ref參數,則設置Referer頭,否則自動設置Referer頭
if($referer) {
curl_setopt($curl, CURLOPT_REFERER, $referer);
} else {
curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
}
//如果有post數據參數,則方法為POST,並且設置數據,否則為GET
if($post) {
//發送一個常規的POST請求,默認類型為:application/x-www-form-urlencoded,www.111cn.net表單提交
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
}
//如果有cookie參數,則設置
if($cookie) {
curl_setopt($curl, CURLOPT_COOKIE, $cookie);
}
//如果有cookie文件參數,則設置存取Cookie文件名
if($cookiejar) {
curl_setopt($curl, CURLOPT_COOKIEJAR, $cookiejar);
curl_setopt($curl, CURLOPT_COOKIEFILE, $cookiejar);
}
//如果是302轉移,則返回轉移後的網址及內容
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
//設置執行的最大秒數
curl_setopt($curl, CURLOPT_TIMEOUT, 100);
//返回內容中是否包含頭信息
curl_setopt($curl, CURLOPT_HEADER, 0);
//把返回的結果存在文件或者變量中,而不是直接顯示在浏覽器
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//執行函數後的返回結果
$tmpInfo = curl_exec($curl);
//如果出錯,顯示錯誤信息
if (curl_errno($curl)) {
$tmpInfo = '<pre><b>錯誤:</b><br />'.curl_error($curl);
}
//關閉curl對象
curl_close($curl);
//返回結果
return $tmpInfo;
}

  例子、soap

 代碼如下   function vcurlsoap($url, $SoapRequest, $SoapAction) {
$ch = curl_init (); //initiate the curl session
curl_setopt ( $ch, CURLOPT_URL, $url ); //set to url to post to
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 ); // return data in a variable
curl_setopt ( $ch, CURLOPT_HEADER, 0 );
curl_setopt ( $ch, CURLOPT_POST, 1 );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $SoapRequest ); // post the xml
curl_setopt ( $ch, CURLOPT_TIMEOUT, 60 ); // set timeout in seconds
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
$header = array ("Content-Type: text/xml" );
$header [] = "Content-Length: ".strlen($SoapRequest);
if (! is_null ( $SoapAction ))
$header [] = 'SOAPAction: "' . $SoapAction . '"';
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $header );
$xmlResponse = curl_exec ( $ch );
curl_close ( $ch );
return $xmlResponse;
}
copyright © 萬盛學電腦網 all rights reserved