【问题标题】:PHP curl exec fail on php script same domainPHP curl exec在php脚本同一域上失败
【发布时间】:2023-03-17 09:30:02
【问题描述】:

我使用 php curl 从同一域 url 中的 php 脚本获取内容。但我得到 curl_exec 错误。 curl 错误代码为 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 = @987654321@ 失败:$url = @987654322@

【问题讨论】:

  • 请显示一些代码,如果可能的话,显示一个超时 URL 的真实代码示例
  • 卷曲代码:$url = 'http://...'; $代理 = ''; $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);打印 "
    \n"; print_r(curl_getinfo($ch)); // 获取错误信息 echo "\n\ncURL 错误编号:" .curl_errno($ch); // 打印错误信息 echo "\n\ncURL error:" . curl_error($ch);打印“
    \n”; curl_close ($ch);回声 $result;
  • cURL 错误号:28 cURL 错误:操作在 8000 毫秒后超时,收到 0 个字节 好的:$url = http://../page.htm。失败:$url = http://.../page.php

标签: php curl


【解决方案1】:

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

另见session.auto-start

【讨论】:

  • 或者在执行 curl_exec 之前执行 session_write_close()。如果会话中的任何内容需要更新,可以在 curl 完成后使用 session_start() 重新打开会话。
  • session_start() 和 session_write_close() 是否仍然失败。
  • 尝试在 page.php 中回显一些简单的东西(回显“foobar”),现在可以了吗?
  • 不,仍然超时。看起来 curl exec 不喜欢来自同一域的 php 脚本,其他纯文件还可以。不知道为什么。
  • 不不,我会检查一下,一切对我来说都可以
【解决方案2】:

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

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

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);
}

【讨论】:

    【解决方案3】:

    设置为 CURL 设置

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

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

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      相关资源
      最近更新 更多