Home  >  Article  >  Backend Development  >  php中我使用curl抓取页面,本地调试都可以,可是放到服务器上就出现400badrequest

php中我使用curl抓取页面,本地调试都可以,可是放到服务器上就出现400badrequest

WBOY
WBOYOriginal
2016-06-06 20:32:552005browse

<code><?php $htmlstr = get_html("https://api.weibo.com/oauth2/access_token?client_id=1233847790&client_secret=c8ba38aa75acc3830fff1eeeb1538723&grant_type=authorization_code&redirect_uri=http://www.yuecong.top&code=55b811f959d2afb495056e7e73f5ba5b");
echo $htmlstr;


function get_html( $url )
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT,120);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1");

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//302redirect

    curl_setopt($ch, CURLOPT_POST, true);//使用post方式
 curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//信任https证书

    $content = curl_exec($ch);

    curl_close($ch);
    return $content;
}
 ?>
</code>

我在自己电脑上用localhost访问是正常返回值的,可是放在服务器上然后去访问浏览器就显示400badrequest

回复内容:

<code><?php $htmlstr = get_html("https://api.weibo.com/oauth2/access_token?client_id=1233847790&client_secret=c8ba38aa75acc3830fff1eeeb1538723&grant_type=authorization_code&redirect_uri=http://www.yuecong.top&code=55b811f959d2afb495056e7e73f5ba5b");
echo $htmlstr;


function get_html( $url )
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT,120);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1");

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//302redirect

    curl_setopt($ch, CURLOPT_POST, true);//使用post方式
 curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//信任https证书

    $content = curl_exec($ch);

    curl_close($ch);
    return $content;
}
 ?>
</code>

我在自己电脑上用localhost访问是正常返回值的,可是放在服务器上然后去访问浏览器就显示400badrequest

首先测试一下非https的链接,比如随便一个网址(http://www.baidu.com),看看是否能获取到内容,如果可以然后再测试一下 https://www.baidu.com,此时如果出现 400 bad request。那么问题应该就是出现 php 的版本上。我们系统曾经碰到类似的问题,php 从5.2.27 升级到 5.3.35 就出现这样的情况,非http正常,https出现问题。问题的原因大概是由于php 跟 openssl 库有冲突。我们的环境是centos。

代码中的 CURLOPT_SSL_VERIFYPEER 不是应该true 吗?

url有没有字符串拼接,看看是不是有换行符什么的

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn