【问题标题】:PHP downloading will randomly give a network errorPHP下载会随机报网络错误
【发布时间】:2023-03-14 09:18:01
【问题描述】:

我目前拥有并运营一个在线 FTP,在租用的服务器上运行,在 PHP 上运行,我正在尝试合并下载(因为这是 FTP 最基本的功能)。我已经使用下面的代码完成了此操作,但是当我尝试下载通常约为 800mb 的服务器备份时,下载有时只会导致网络错误。这是非常烦人和不方便的。我很感激任何关于为什么会发生这种情况的想法。提前致谢!我只有 2GB 内存。

header("Content-Disposition: attachment; filename=\"$name\"");
header("Content-Type: application/octet-stream");
header("Content-Length: ".filesize("ftp://$u:$p@$h".$_GET['data']));
header("Connection: close");
readfile("ftp://$u:$p@$h".$_GET['data']);

【问题讨论】:

  • 多长时间会出现“网络错误”?
  • 如果错误发生是完全随机的,通常发生在下载即将完成之前。
  • 您使用的是 NGINX 或 Apache2 还是其他服务器?

标签: php download ftp header


【解决方案1】:

您需要为 PHP 和 Web 服务器设置限制

在 PHP 中

// add these in starting of the files
ini_set('memory_limit', '1G'); //according to your requirements
//only for development will show some extra debug info.
ini_set('display_errors', true);
ini_set('max_execution_time', 0); //0=NOLIMIT

我们还必须在 Web 服务器级别设置这些设置(时间和大小),我假设您使用的是 NGINX

在网络服务器中(vi /etc/nginx/nginx.conf)

keepalive_timeout  60; #try this with 600, i thing your issue belongs here
send_timeout 60; #try this with 600, i thing your issue belongs here
client_body_timeout 120; #try this with 600, i thing your issue belongs here
client_max_body_size 5G; #default is 4.5 GB so you dont need this if data is less than 4.5GB

Web 服务器更改后不要忘记重启 NGINX。

有关 nginx 限制的更多信息click here

【讨论】:

  • 我的服务器使用的是 Apache,所以这不适用于我。
  • @GriffinGarman 那么你需要在 apache2 级别设置响应超时和响应大小
  • 在 cmd sudo tail -1000f /var/log/apache2/error.log 中运行此命令,然后尝试下载您的文件,如果您在 apache 级别遇到任何错误,那么它将出现在您的 CMD 中跨度>
  • 还要确保output_buffering=0.
【解决方案2】:

尝试将header('Expires: 0');set_time_limit(0); 放在readfile() 之前,看看是否有帮助。

至于压缩,我相信您首先需要在压缩之前将文件下载到服务器。

不确定是否有免费的替代品,但 Chilkat 有 FTP 和文件压缩(Zip、GZip 或 TAR)

压缩示例:https://www.example-code.com/phpExt/tar_create_bz2.asp

【讨论】:

  • 您好,感谢您的回答,您能否详细说明为什么添加header('Expires: 0');set_time_limit(0); 会有所帮助。只是为了让我能更好地理解。
  • 我实现了你的代码,但它似乎没有改变任何东西。
  • header('Expires: 0'); 只是意味着缓存将永远是陈旧的(即它需要先重新验证它才能将其返回给客户端)参见docs.oracle.com/cd/E13158_01/alui/wci/docs103/devguide/…set_time_limit(0) 限制最大执行时间,f 设置为零,没有时间限制。 php.net/manual/en/function.set-time-limit.php
  • 您是否在开发控制台 (F12) 中看到任何内容,或者您​​是否可以在网络服务器上运行 Wireshark/网络捕获并跟踪 FTP 连接。理想情况下想知道连接是否被 FTP 服务器、Web 服务器或客户端丢弃
  • chrome 检查器工具的网络选项卡中没有记录任何内容。我下载了 wireshark,它似乎是一个有用的实用程序。然后我下载了 6 个服务器备份,其中 3 个因网络错误而失败。你能给我解释一下吗:> 38 0.000609 192.168.0.31 31.22.4.131 TCP 66 60228 → 443 [ACK] Seq=127 Ack=15929 Win=32632 Len=0 TSval=1412756963 TSecr=346646704
【解决方案3】:

由于您尝试一次下载多个文件,而您只有 2gb 的 RAM,租用的服务器很可能会切断连接。

【讨论】:

    猜你喜欢
    • 2014-12-17
    • 2013-12-06
    • 1970-01-01
    • 2017-12-22
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多