1.cURL介紹
cURL 是一個利用URL文法規定來傳輸檔案和資料的工具,支援很多協定,如HTTP、FTP、TELNET等。最爽的是,PHP也支援 cURL 庫。本文将介紹 cURL 的一些進階特性,以及在PHP中如何運用它。
2.基本結構
在學習更為複雜的功能之前,先來看一下在PHP中建立cURL請求的基本步驟:
(1)初始化 curl_init()
(2)設定變量 curl_setopt() 。最為重要,一切玄妙均在此。有一長串cURL參數可供設定,它們能指定URL請求的各個細節。要一次性全部看完并了解可能比較困難,是以今天我們隻試一下那些更常用也更有用的選項。
(3)執行并擷取結果 curl_exec()
(4)釋放cURL句柄 curl_close()
3.cURL實作Get和Post
3.1 Get方式實作
複制代碼 代碼如下:
//初始化
$ch = curl_init();
//設定選項,包括URL
curl_setopt($ch, CURLOPT_URL, "http://www.jb51.net");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
//執行并擷取HTML文檔内容
$output = curl_exec($ch);
//釋放curl句柄
curl_close($ch);
//列印獲得的資料
print_r($output);
3.2 Post方式實作
$url = "http://localhost/web_services.php";
$post_data = array ("username" => "bob","key" => "12345");
curl_setopt($ch, CURLOPT_URL, $url);
// post資料
curl_setopt($ch, CURLOPT_POST, 1);
// post的變量
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
以上方式擷取到的資料是json格式的,使用json_decode函數解釋成數組。
$output_array = json_decode($output,true);
如果使用json_decode($output)解析的話,将會得到object類型的資料。
3.3 關于curl上傳檔案
在localhost根目錄建立1.php如下:
複制代碼
<?php
$ch=curl_init('http://localhost/post.php');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// localhost:8888是fiddler的代理,設定此選項用于讓fiddler抓獲post的請求
curl_setopt($ch, CURLOPT_PROXY, 'localhost:8888');
//下面這一句必須注釋,不然Fiddler抓不到Post的http請求
//curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
//1.檔案路徑之前必須要加@
//2.檔案路徑帶中文就會失敗,例如'img_1'=>'@C:\Documents and Settings\Administrator\桌面\Android桌面\androids.gif'
array('uname'=>'wqfghgfh','img_1'=>'@C:\Documents and Settings\Administrator\androids.gif')
);
$data=curl_exec($ch);
curl_close($ch);
echo $data;
?>
在localhost根目錄建立post.php如下
var_dump($_POST);
var_dump($_FILES);
?>
通路http://localhost/1.php,傳回如下内容:
array 'uname' => string 'wqfghgfh' (length=8)
array 'img_1' => array 'name' => string 'androids.gif' (length=12) 'type' => string 'application/octet-stream' (length=24) 'tmp_name' => string 'C:\WINDOWS\Temp\php1BE.tmp' (length=26) 'error' => int 0 'size' => int 11293