简单示例:
/** * @param $url * @return array * 进行https请求,并且遇到location进行跳转 */ function https($url){ $result = array(); $UA = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);//直接跳转到location指定的页面 curl_setopt($ch, CURLOPT_USERAGENT, $UA); $result['http_content'] = curl_exec($ch); $result['location'] = curl_getinfo($ch,CURLINFO_EFFECTIVE_URL); curl_close($ch); return $result; }
一个更好的https请求类:
<?php /* * @brief url封装类,将常用的url请求操作封装在一起 * */ class URL{ private $error; public function __construct(){ //$this->error = new ErrorCase(); } /** * combineURL * 拼接url * @param string $baseURL 基于的url * @param array $keysArr 参数列表数组 * @return string 返回拼接的url */ public function combineURL($baseURL,$keysArr){ $combined = $baseURL."?";//拼接? $valueArr = array(); //拼接参数 foreach($keysArr as $key => $val){ $valueArr[] = "$key=$val"; } //将参数拼接为字符串 $keyStr = implode("&",$valueArr); //拼接为完整的URL $combined .= ($keyStr); return $combined; } /** * get_contents * 服务器通过get请求获得内容 * @param string $url 请求的url,拼接后的 * @return string 请求返回的内容 */ public function get_contents($url){ if (ini_get("allow_url_fopen") == "1") { $response = file_get_contents($url); }else{ $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_URL, $url); $response = curl_exec($ch); curl_close($ch); } //-------请求为空 if(empty($response)){ //$this->error->showError("50001"); } return $response; } /** * get * get方式请求资源 * @param string $url 基于的baseUrl * @param array $keysArr 参数列表数组 * @return string 返回的资源内容 */ public function get($url, $keysArr){ $combined = $this->combineURL($url, $keysArr); return $this->get_contents($combined); } /** * post * post方式请求资源 * @param string $url 基于的baseUrl * @param array $keysArr 请求的参数列表 * @param int $flag 标志位 * @return string 返回的资源内容 */ public function post($url, $keysArr, $flag = 0){ $ch = curl_init(); if(! $flag) curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_POST, TRUE); curl_setopt($ch, CURLOPT_POSTFIELDS, $keysArr); curl_setopt($ch, CURLOPT_URL, $url); $ret = curl_exec($ch); curl_close($ch); return $ret; } }