本地测试的时候完全没问题,放到服务器就遇到返回false。
网上查了些资料。改了下代码。能够完全运行了。
拷贝过去研究研究能看懂的
//定义一个全局变量
public $cookie="";
//登录接口,获取cookie
public function SendPost($url,$data=[]){
$re = $this->post_curl($url , $data,1);
//var_dump($re);
// 解析HTTP数据流
list($header, $body) = explode("\r\n\r\n", $re);
// 解析COOKIE
preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches);
//请求的时候headers 带上cookie就可以了
if ($matches){
$cookie = explode(';', $matches[1])[0];
$this->cookie = trim($cookie);
}
return $body;
}
//发送请求方法POST
function post_curl($url, $params=[], $isShowHeader=0){
$httpInfo = array();
$ch = curl_init();
curl_setopt( $ch, CURLOPT_HEADER, $isShowHeader);
curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36' );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
curl_setopt( $ch , CURLOPT_POST , true );
curl_setopt( $ch , CURLOPT_POSTFIELDS , http_build_query($params));
curl_setopt( $ch , CURLOPT_URL , $url );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
if($this->cookie){
curl_setopt($ch, CURLOPT_COOKIE, $this->cookie);//设置cookie
}
$response = curl_exec( $ch );
if ($response === FALSE) {
return false;
}
curl_close( $ch );
return $response;
}