1. curl的安裝配置:
Linux下的安裝:
http://php.net/manual/zh/curl.setup.php
windows下的安裝:
開啟:
extension=php_curl.dll //注意對應版本的 dll 檔案
2. curl 使用步驟
具體的參數使用資訊 請參閱:http://php.net/manual/zh/book.curl.php
3. 部分使用案例
3.1 使用https 時 需要對認證認證進行過濾
curl->options(array(CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false));?>
3.2 使用 body(一般對於java 的認證方式) 傳輸介面時 使用下面的方法
/** * 普通函數傳遞方式(已做認證跳過) * 調用基礎: * $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken"; * $res = json_decode($this->httpGet($url)); */private function httpGet($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); return $res; } /** * java 的body 認證傳輸方式 * 調用基礎: * $result = list($return_code, $return_content) = $this->http_post_data($url, json_encode(array("Key"=>$pass))); * $res = json_decode($return_content); * $return_code = $res->rspMsg; */ public function http_post_data($url, $data_string) { $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen($data_string)) ); ob_start(); curl_exec($ch); $return_content = ob_get_contents(); ob_end_clean(); $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); return array($return_code, $return_content); }
3.3 CI架構中 CURL的調試 方式
$this->curl->debug();
3.4 CURL 類比檔案上傳 (音效檔上傳)
$soundurl = '你本地聲音路徑的絕對位址 如:/data/sound/ins.amr'; //初始化 $ch = curl_init(); //檔案路徑地址 $furl = "@".$soundurl; $post_data = array ( "media" => $furl ); //提交檔案地址 $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$token."&type=voice"; //設定變數 curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//執行結果是否被返回,0是返回,1是不返回 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); //執行並擷取結果 $output = curl_exec($ch); if($outopt === FALSE){ echo "
","cUrl Error:".curl_error($ch); } curl_close($ch); $obj = json_decode($output);
3.5 音效檔的本地 下載
$soundfile = $this->curl->simple_get("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$token."&media_id=".$soundid); $soundurl = "./sound/".$id.".amr"; file_put_contents($soundurl, $soundfile);