php curl函数_PHP curl函数_解决curl返回空白问题

最后更新:2019-12-17 16:32:45 星期二

修复事项:网页显示空白问题,https ssl证书校验所致

在使用php开发过程中经常会需要使用curl进行获取远程页面或接口输出结果,也常用于数据抓取及采集。考虑到复用性,封装函数如下:

```php

/**

* CURL请求函数:支持POST及基本header头信息定义

* @Author 未来往事 2016-09-12

* @param [api_url:目标url | post_data:post参数 | header:头信息数组 | referer_url:来源url]

* @return [code:状态码(200执行成功、400执行异常) | data:数据]

*/

function curl_request($api_url, $post_data = [], $header = [], $referer_url = ''){

$ch = curl_init();//初始化CURL句柄

curl_setopt( $ch, CURLOPT_URL, $api_url);

/**配置返回信息**/

curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);//获取的信息以文件流的形式返回,不直接输出

curl_setopt( $ch, CURLOPT_HEADER, 0);//不返回header部分

/**配置超时**/

curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10);//连接前等待时间,0不等待

curl_setopt( $ch, CURLOPT_TIMEOUT, 5);//连接后等待时间,0不等待。如下载mp3

/**配置页面重定向**/

curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);//跟踪爬取重定向页面

curl_setopt( $ch, CURLOPT_MAXREDIRS, 10);//指定最多的HTTP重定向的数量

curl_setopt( $ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer

/**配置Header、请求头、协议信息**/

curl_setopt( $ch, CURLOPT_HTTPHEADER, $header);

curl_setopt( $ch, CURLOPT_ENCODING, "");//Accept-Encoding编码,支持"identity"/"deflate"/"gzip",空支持所有编码

curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)" );//模拟浏览器头信息

$referer_url && curl_setopt( $ch, CURLOPT_REFERER, $referer_url);//伪造来源地址

//curl_setopt( $ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 ); //设置curl使用的HTTP协议

/**配置POST请求**/

if($post_data && is_array($post_data)){

curl_setopt( $ch, CURLOPT_POST, 1 );//支持post提交数据

curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query($post_data));//

}

/**禁止证书验证防止curl输出空白**/

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//禁止 cURL 验证对等证书

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//是否检测服务器的域名与证书上的是否一致

$code = 200; //执行成功

$data = curl_exec( $ch );

//捕抓异常

if (curl_errno($ch)) {

$code = 400; //执行异常

$data = curl_error($ch);

}

curl_close( $ch );

return ['code' => $code, 'data' => $data];

}

```

调用示例:

```php

$url = 'https://www.fity.cn';

$post_data = [

'cache'=>0

];

$header = [

'CLIENT-IP: 100.0.0.0',

'X-FORWARDED-FOR: 100.0.0.0',

];

$referer_url = 'http://www.fity.cn';

$res = curl_request($url, $post_data, $header, $referer_url);

if($res['code'] == 200){

print_r($res['data']);

}else{

//异常处理

}

```

如本篇文章未能解决你遇到的问题,建议你同时参考《[curl无输出_返回空白_返回77问题解决](https://www.fity.cn/post/673.html "curl无输出_返回空白_返回77问题解决")》

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值