php封装curl,模拟POST和GET请求HTTPS请求

<?php

/**
* @title 封装代理请求
* @author victor
**/
class ApiRequest { /**
* curl提交数据
* @param String $url 请求的地址
* @param Array $header 自定义的header数据
* @param Array $content POST的数据
* @return String
*/
public function toCurl($url, $header, $content)
{
$ch = curl_init();
if(substr($url,0,5)=='https'){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 跳过证书检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content));
$response = curl_exec($ch);
if($error=curl_error($ch)){
die($error);
}
curl_close($ch);
return $response;
} /**
* @desc GET请求
**/
public function curl_get($url, array $params = array(), $timeout = 5)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
} /**
* @desc POST请求
**/
public function curl_post($url, array $params = array(), $timeout)
{
$ch = curl_init();//初始化
curl_setopt($ch, CURLOPT_URL, $url);//抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$data = curl_exec($ch);//运行curl
curl_close($ch);
return ($data);
} /**
* @desc https 请求
**/
public function curl_get_https($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11');
$res = curl_exec($ch);
$rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $res;
}
}
?>

调用:

public function proxyTest()
{
$ApiReq = new ApiRequest(); //该网站的接口地址;
$url = 'https://www.xxx.com/ajax/fx.do'; //模拟header内容
$header = array(
'Host: www.domain.com',
'Origin: https://www.domain.com',
'Referer: https://www.domain.com/',
'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
'X-Requested-With: XMLHttpRequest'
);
// post请求参数
$content = array(); //curl模拟提交
$response = $ApiReq -> toCurl($url, $header, $content);
$response = json_decode($response,true);
return $response;
}
上一篇:js怎么能取得多选下拉框选中的多个值?


下一篇:Rust 之 cargo(项目构建和包管理工具)