php curl:带证书https方式的curl请求,以及需要cookie存储和读取的请求

技术分享 · Fecmall · 于 6年前 发布 · 7271 次阅读

访问xxx网站,用的https方式,需要证书,并且需要cookie这种神奇的方式,前面不能通过,后面发现 居然需要cookie,不然就返回一团乱麻:

后面参考了资料,发现我本地也有一个rbzid的cookie

https://stackoverflow.com/questions/28139457/unexpected-result-from-php-request

将代码中添加了cookie的获取和存放,然后通过,代码如下:

public static function updateCookieFile($url,$refer,$data){
		
		$headers = array (
			'Content-Type: application/json',
			'Host: hub.xxx.com' ,
        );
		
		$crt_dir = Yii::getAlias('@common')."/lib/xxx.com/COMODORSACertificationAuthority.crt";
		//$crt_dir = Yii::getAlias('@common').'/lib/xxx.com/cacert.pem';
		
		//echo $crt_dir;exit;
		
		$timeout = 30;
		//对空格进行转义
		//$url = str_replace(' ','+',$url);
		$ch = curl_init();
		//设置选项,包括URL
		curl_setopt($ch, CURLOPT_URL, "$url");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0');
		curl_setopt($ch, CURLOPT_REFERER, $refer);
		curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
		$cookie_file = Yii::getAlias('@common')."/lib/xxx.com/cookie_file.txt";
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);    //存cookie的文件名,
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
        // 下面是https方式加入证书的部分, $crt_dir 是本地的证书绝对路径
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($ch, CURLOPT_CAINFO, $crt_dir);

		curl_setopt($ch,CURLOPT_TIMEOUT,$timeout);  //定义超时3秒钟  
		// POST数据
		curl_setopt($ch, CURLOPT_POST, 1);
		// 把post的变量加上
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		//执行并获取url地址的内容
		$output = curl_exec($ch);
		//echo $output ;
		//释放curl句柄
		curl_close($ch);
		//return $output;
	
		return $output;
	}
共收到 1 条回复 技术分享
Fecmall#16年前 0 个赞

主要是需要添加:

$cookie_file = Yii::getAlias('@common')."/lib/xxx.com/cookie_file.txt";
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);    //存cookie的文件名,
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);

我们的脚本,第一次请求是获取token,因此,在获取token前先通过上面的方法,先刷一下cookie到文件, 然后,整个脚本后面的访问请求,就把存cookie的这行代码去掉,

curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);    //存cookie的文件名,

只保留读取cookie的部分即可。

$cookie_file = Yii::getAlias('@common')."/lib/xxx.com/cookie_file.txt";
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册
Your Site Analytics