PHP / Codeigniter FTP超时

时间:2010-06-12 13:53:28

标签: php codeigniter ftp execution

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

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

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

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

Codeigniter的ftp类使用底层的ftp_connect php调用,该调用支持第三个可选参数timeout(http://ca2.php.net/manual/en/function.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
}

除非在te配置数组中将debug参数设置为TRUE,否则ftp类不会提供错误消息,在这种情况下它只会显示错误。但它也可以覆盖,因为所有错误都会调用类中的函数_error()。所以你可以设置'debug'=&gt;在$ ftp_params数组中为true,并在MY_ftp中添加一个函数,如下所示:

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

然后有一个函数getError()     / **      *此功能覆盖      * /     function get_error()     {         返回$ this-&gt;错误;     }

所以,如果

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

返回false,您可以调用

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

获取错误并显示错误。 现在,您可以通过进一步自定义类来自定义并具有更复杂的错误处理机制......

希望它能回答你的问题。

答案 1 :(得分:-1)

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