http請求包括兩種,一種是我們普通的http請求登錄,另一種是另一種https請求登錄,下面我來分別給各位同學詳細介紹利用curl_init來實現http與https進行登錄。
備注:使用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.49028c.com/';
- $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;
- }
- }
新聞熱點
疑難解答