PHP curl exec在php脚本同一域上失败

时间:2011-02-26 17:04:38

标签: php curl

我使用php curl从同一域url中的php脚本获取内容。但我得到curl_exec错误。卷曲错误代码为28或操作超时。经过几天的调试,我发现它可以在非脚本页面上工作,比如htm,但不是php,如果url是不同域上的脚本,它也可以工作。我已经调试了几天,没有找到解决方案。帮助赞赏。

$url = 'http://...';
$agent = '';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
curl_setopt($ch, CURLOPT_TIMEOUT, 8);
$result = curl_exec ($ch);
print "<pre>\n";
print_r(curl_getinfo($ch));
// get error info echo "\n\ncURL error number:" .curl_errno($ch);
// print error info echo "\n\ncURL error:" . curl_error($ch);
print "</pre>\n";
curl_close ($ch);
echo $result;

cURL错误号:28 cURL错误:

  

8000后操作超时   收到0字节的毫秒数

好的:$url = http://.../page.htm 失败:$url = http://.../page.php

3 个答案:

答案 0 :(得分:6)

您没有设置用户代理。有些服务器实际上甚至不响应这些请求(因此客户端不知道连接丢失了)。

将以下内容添加到您的代码中:

curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);

此外,我在我的CURL功能中使用以下内容:

curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
curl_setopt($ch,CURLOPT_MAXREDIRS,50);
if(substr($url,0,8)=='https://'){
    // The following ensures SSL always works. A little detail:
    // SSL does two things at once:
    //  1. it encrypts communication
    //  2. it ensures the target party is who it claims to be.
    // In short, if the following code is allowed, CURL won't check if the 
    // certificate is known and valid, however, it still encrypts communication.
    curl_setopt($ch,CURLOPT_HTTPAUTH,CURLAUTH_ANY);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
}

答案 1 :(得分:1)

可能是因为会话锁定 尝试从您尝试使用cURL的页面中删除session_start()

另见session.auto-start

答案 2 :(得分:1)

设置为CURL设置

curl_setopt($ch, CURLOPT_TIMEOUT, 300); // 300 seconds

如果仍有问题,请运行脚本并禁用以下位置。

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);