備忘:使用curl_init函數,必須要開啟這個php擴充。
1.開啟php.ini,開啟extension=php_curl.dll
2.檢查php.ini的extension_dir值是哪個目錄,檢查有無php_curl.dll,沒有的請下載php_curl.dll,再把php目錄中的libeay32.dll,ssleay32.dll拷到c:/windows/system32裡面。
發起http請求
| 代碼如下 |
複製代碼 |
function _http_curl_post($url,$data) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 4); curl_setopt($ch, CURLOPT_TIMEOUT,4); if($data){ curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, "value=".json_encode($data)); //請求參數轉為json格式 } curl_setopt($ch, CURLOPT_HEADER, false); $string = curl_exec($ch); curl_close($ch); return $string; } |
調用方法
| 代碼如下 |
複製代碼 |
$params = array(); $params['id'] = 1 $params['web_name'] = '好指令碼'; $params['web_url'] = 'http://www.111cn.net/'; $params['web_miaoshu'] = '指令碼編程樣本'; $data = _curl_post($url,$params); $arr =json_decode($data); |
除了http請求之外還有一個https的請求,上次我做人人網的一鍵登入,它的介面就是https的url,使用上面的函數,最終報錯。如果您也遇到這樣的問題,你可以參考下面方法解決。
https請求樣本
| 代碼如下 |
複製代碼 |
function _https_curl_post($url, $vars) { foreach($vars as $key=>$value) { $fields_string .= $key.'='.$value.'&' ; } $fields_string = substr($fields_string,0,(strlen($fields_string)-1)) ; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // this line makes it work under https curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_POST, count($vars) ); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); $data = curl_exec($ch); curl_close($ch); if ($data) { return $data; } else { return false; } } |