1

我正在尝试使用 Codeigniter 的 FTP 库从我的 PHP 脚本访问 FTP 服务器。这些功能很好用,但是在测试脚本时,我发现如果我尝试连接到不存在的服务器,脚本不会以任何类型的错误消息终止。

页面继续执行,直到 Web 服务器放弃,返回一个空文档。

所以我想知道,有没有办法限制 Codeigniter 可以尝试连接到 FTP 服务器的时间,然后在超时时显示一条消息?

我尝试使用 php 函数 set_time_limit(),但它的行为并不符合我的预期。

谢谢你的帮助。

4

2 回答 2

3

Codeigniter 的 ftp 类使用支持第三个可选参数 timeout ( http://ca2.php.net/manual/en/function.ftp-connect.php ) 的底层 ftp_connect php 调用。

然而,Codeigniter 不使用它,但允许扩展它提供的默认库(前提是您愿意做一些工作并检查您对核心所做的任何更新都不会破坏扩展类的功能)。因此,要解决您的问题,您可以在应用程序库文件夹中创建一个新库:

<?php

class MY_FTP extends CI_FTP { //Assuming that in your config.php file, your subclass prefix is set to 'MY_' like so: $config['subclass_prefix'] = 'MY_';

    var $timeout = 90;
    /**
     * FTP Connect
     *
     * @access  public
     * @param   array    the connection values
     * @return  bool
     */
    function connect($config = array())
    {
        if (count($config) > 0)
        {
            $this->initialize($config);
        }

        if (FALSE === ($this->conn_id = ftp_connect($this->hostname, $this->port, $this->timeout)))
        {
            if ($this->debug == TRUE)
            {
                $this->_error('ftp_unable_to_connect');
            }
            return FALSE;
        }

        if ( ! $this->_login())
        {
            if ($this->debug == TRUE)
            {
                $this->_error('ftp_unable_to_login');
            }
            return FALSE;
        }

        // Set passive mode if needed
        if ($this->passive == TRUE)
        {
            ftp_pasv($this->conn_id, TRUE);
        }

        return TRUE;
    }
}
?>

并从您的脚本中,您可以将超时选项添加到配置数组中:

$this->load->library('ftp'); //if ftp is not autoloaded
$ftp_params = array('hostname'=>'1.2.3.4', 'port'=>21, 'timeout'=>10); //timout is 10 seconds instead of default 90
$ftp_conn = $this->ftp->connect($ftp_params);
if(FALSE === $ftp_conn) {
//Code to handle error
}

ftp 类并非设计用于提供错误消息,除非在配置数组中将 debug 参数设置为 TRUE,在这种情况下它只会显示错误。但是它也可以被覆盖,因为所有错误都会调用类中的函数 _error()。因此,您可以在 $ftp_params 数组中设置 'debug' => true ,然后在 MY_ftp 中添加一个函数,如下所示:

/**
 * This function overrides 
 */
function _error($line)
{
    $this->error = $line;
}

然后有一个函数 getError() /** * 这个函数覆盖 */ function get_error() { return $this->error; }

因此,如果

$ftp_conn = $this->ftp->connect($ftp_params);

返回false,你可以调用

$error = $this->ftp->get_error();

得到你的错误并显示它。现在,您始终可以通过进一步自定义类来自定义并拥有更复杂的错误处理机制......

希望它能回答你的问题。

于 2010-06-12T18:19:32.810 回答
-1

答案很简单,不要尝试连接不存在的服务器

于 2010-06-12T14:01:25.723 回答