如何限制FTP连接时间

How to limit FTP connection time

我有 FTP 服务器,IP 地址为 public,比方说:192.0.0.12。但在一些不同网络的地区,连接到这个IP是不适用的。在这种情况下,我们可以通过另一个 IP 连接到 FTP,比方说:171.0.0.13。

所以我在 PHP 中编写了脚本以连接到 FTP 服务器并使用 ftp_connect() 下载文件。为了避免长时间响应,我使用 set_time_limit() 将时间限制设置为 5 秒。这是脚本:

<?php
include "config.php";
function ftp_konek($ftp_server){
    set_time_limit(5);
    $conn_id = ftp_connect($ftp_server);
    return $conn_id;
}
if(ftp_konek($ftp_server)){
    /*download the file*/
}else{
    $ftp_server = "171.0.0.13";
    $change_ip = ftp_konek($ftp_server);
    if($change_ip){
       /*download the file*/
    }else{
       echo "Failed!";
    }
}
?>

public IP和用户名+密码存储在config.php中。思路是:

  1. 使用第一个 IP 连接到 FTP 服务器。
  2. 如果 5 秒内成功,请下载文件。
  3. 否则,如果不成功,请更改 FTP 服务器 IP 并连接。
  4. 如果连接成功,下载文件

问题是,我收到警告:

Fatal error: Maximum execution time of 5 seconds exceeded

并且操作停止了。

有什么想法吗?

好的,已经注意了!

您的脚本最长执行时间为 5 秒,非常短。 ftp_connect 的默认超时为 90 秒,因此显然存在一些问题。

改变

$conn_id = ftp_connect($ftp_server);

$conn_id = ftp_connect($ftp_server, 21, 2);

它可能会起作用。我还希望将最大执行时间设置得更高。如果将其放在脚本的开头:

set_time_limit(30);

那么你可以使用更合理的超时时间

$conn_id = ftp_connect($ftp_server, 21, 10);

ftp_connect 函数有 $timeout 个参数。

设置它而不是通过限制 PHP 执行时间来破解它。

ftp_connect($ftp_server, 21, 5);

set_time_limit 为整个脚本设置全局时间限制 而不仅仅是 ftp_connectftp_connect 有自己的第三个参数 $timeout:

$conn_id = ftp_connect($ftp_server, 21, 5);