Location: PHPKode > scripts > nfFTP > nfftp/nfFTP.class.php
<?php

// +----------------------------------------------------------------------+
// | Neutrino PHP Web Development Framework                               |
// +----------------------------------------------------------------------+
// | Neutrino is licensed using LGPL.                                     |
// +----------------------------------------------------------------------+
// | Author  : Ben Bi (from GuangZhou of China)                           |
// | Email   : hide@address.com                                       |
// | Homepage: http://neutrinophp.sourceforge.net                         |
// | SVN: https://opensvn.csie.org/neutrinophp/trunk                      |
// +----------------------------------------------------------------------+
/**
* FTP Client Handler
* 
* nfFTP mainly used to establish the connection to FTP server.
* this class has contain more useful funtion to handler the 
* FTP operations
*
* @version 	nfFTP.class.php, v1.0,  2008-01-08 18:53:45
* @package	
*/

class nfFTP
{
    public $host;
    public $port = 21;
    public $user;
    public $password;
    public $connectionId;
    public $localPath = '';
    public $remotePath = '';
    public $sysType = '';
    public $transferMode = FTP_BINARY;
    public $connected = FALSE;
    public $defaultSettings = array();
    public $defaultMode = "0777";

    /**
    * nfFTP class constructor
    *
    * @access  public
    *
    */
    public function __construct()
    {
        if (!extension_loaded("ftp"))
        {
            trigger_error("Error: unsurpport extension", E_USER_ERROR);
        }

    }

    /**
    * Set the ftp server
    *
    * @access  public
    *
    */

    public function setServer($host, $port=21)
    {
        if ($this->isConnected()) return FALSE;
        $this->host = $host;
        $this->port = intval($port);
    }

    /**
    * Set the user authorized info of FTP server
    *
    * @access  public
    *
    */
    public function setUserInfo($user, $password) {
        if ($this->isConnected()) return FALSE;
        $this->user = $user;
        $this->password = $password;
    }

    /**
    * Set the transfer mode (FTP_ASCII or FTP_BINARY)
    *
    * @access  public
    *
    */
    public function setTransferMode($mode)
    {
        if (in_array($mode, array(FTP_ASCII, FTP_BINARY))) {
            $this->transferMode = $mode;
        }
    }

    /**
    * Get the current Directory (such as command pwd in ftp system)
    *
    * @access  public
    *
    */

    public function getCurrentDir() {
        if (!empty($this->remotePath)) {
            return $this->remotePath;
        } else if (!$this->isConnected()) {
            return FALSE;
        } else {
            $path = ftp_pwd($this->connectionId);
            if (!$path) {
                $this->remotePath = null;
                return FALSE;
            } else {
                $this->remotePath = $path;
                return $this->remotePath;
            }
        }
    }

    public function fileNbGet($filePointer, $remoteFile, $mode = NULL)
    {
        if (!$this->isConnected())
        {
            return false;
        }
        else if (!is_resource($filePointer))
        {
            trigger_error('ERR_INVALID_RESOURCE',E_USER_ERROR);
        }
        else
        {
            $ret = ftp_nb_fget($this->connectionId, $filePointer, $remoteFile, $mode);
            while ($ret == FTP_MOREDATA)
            {

                // Do whatever you want
                $this->debugPrintOut(".", false);

                // Continue downloading...
                $ret = ftp_nb_continue($this->connectionId);
            }
            if ($ret != FTP_FINISHED) {
                $this->debugPrintOut("There was an error when downloading the file...");
                return false;
            }
            else {
                return true;
            }
        }
    }

    /**
    * Get the system type
    *
    * @access  public
    *
    */
    public function getSysType()
    {
        if (!empty($this->sysType)) {
            return $this->sysType;
        } else if (!$this->isConnected()) {
            return FALSE;
        } else {
            $sysType = ftp_systype($this->connectionId);
            if (!$sysType) {
                $this->sysType = null;
                return FALSE;
            } else {
                $this->sysType = $sysType;
                return $this->sysType;
            }
        }
    }

    /**
    * Check the connection whether connected
    *
    * @access  public
    *
    */
    public function isConnected()
    {
        return $this->connected;
    }

    /**
    * Establish connection
    *
    * @access  public
    *
    */
    public function connect()
    {
        if ($this->isConnected()) {
            $this->quit();
        }
        if (!isset($this->host))
        {
            trigger_error("Error: missing ftp host",E_USER_ERROR);

        } else {
            $this->connectionId = @ftp_connect($this->host, $this->port);
            if (!$this->connectionId)
            {
                return FALSE;
            }
            else
            {
                $this->connected = TRUE;
                return TRUE;
            }
        }
    }

    /**
    * Execute the login public function to log on the FTP server
    *
    * @access  public
    *
    */
    public function login($anonymous = FALSE)
    {
        if (!$this->isConnected())
        {
            $this->connect();
        }
        if ((!isset($this->user) || !isset($this->password)) && !$anonymous)
        {
            trigger_error("Error: missing user or password",E_USER_ERROR);

        }
        else
        {
            $authUser = ($anonymous) ? 'anonymous' : $this->user;
            $authPass = ($anonymous) ? 'hide@address.com' : $this->password;
            return @ftp_login($this->connectionId, $authUser, $authPass);
        }
    }

    /**
    * Restart the connection of FTP server
    *
    * @access  public
    *
    */
    public function restart()
    {
        if ($this->isConnected()) {
            $this->quit();
        }
        foreach($this->defaultSettings as $property => $value) {
            $this->$property = $value;
        }
        unset($this->host);
        unset($this->user);
        unset($this->password);
        unset($this->connectionId);
    }

    /**
    * Quit the FTP server
    *
    * @access  public
    *
    */
    public function quit()
    {
        if (!$this->isConnected()) {
            return FALSE;
        } else {
            $return = @ftp_quit($this->connectionId);
            unset($this->connectionId);
            return $return;
        }
    }
    /**
    * Execute the site command
    *
    * @access  public
    *
    */
    public function site($command)
    {
        if ($this->isConnected()) {
            return @ftp_site($this->connectionId, $command);
        } else {
            return FALSE;
        }
    }

    /**
    * Toggle the passive mode of FTP server
    *
    * @access  public
    *
    */
    public function togglePassiveMode($mode)
    {
        if ($this->isConnected()) {
            return @ftp_pasv($this->connectionId,(bool)$mode);
        } else {
            return FALSE;
        }
    }

    /**
    * Change directory
    *
    * @access  public
    *
    */
    public function changeDir($directory)
    {
        try
        {
            if (!$this->isConnected())
            {
                return FALSE;
            }
            else
            {
                $return = @ftp_chdir($this->connectionId, $directory);
                if (!$return)
                {
                    return FALSE;
                }
                else
                {
                    $this->remotePath = @ftp_pwd($this->connectionId);
                    return TRUE;
                }
            }
        }
        catch(Exception $e)
        {
            trigger_error("error when changeDir {$directory}",E_USER_ERROR);
        }
    }

    /**
    * Change the directory which up
    *
    * @access  public
    *
    */
    public function changeDirUp()
    {
        if (!$this->isConnected()) {
            return FALSE;
        } else {
            $return = @ftp_cdup($this->connectionId);
            if (!$return) {
                return FALSE;
            } else {
                $this->remotePath = @ftp_pwd($this->connectionId);
                return TRUE;
            }
        }
    }
    /**
    * Create the directory.$moveDir is true means it'll build the directory and change to there
    *
    * @access  public
    *
    */
    public function makeDir($directory, $moveDir = FALSE)
    {
        if (!$this->isConnected()) {
            return FALSE;
        }
        else
        {
            $return = @ftp_mkdir($this->connectionId, $directory);

            if ($moveDir)
            {
                $this->changeDir($directory);
            }

            if (!$return)
            {
                return FALSE;
            }
            else
            {
                return TRUE;
            }
        }
    }

    public function getSize($file)
    {
        if (!$this->isConnected())
        {
            return FALSE;
        }
        else
        {
            return ftp_size($this->connectionId, $file);
        }
    }


    /**
    * Remove the directory
    *
    * @access  public
    *
    */
    public function removeDir($directory)
    {
        if (!$this->isConnected()) {
            return FALSE;
        } else {
            return @ftp_rmdir($this->connectionId, $directory);
        }
    }

    public function deltree($directory, $isDelTagDir=true)
    {
        $this->changeDir($directory);
        $this->removeDirRecursive("./");
        if($isDelTagDir)
        {
            $this->removeDir($directory);
        }
    }

    /**
    * Remove the directories (include sub-directories)
    *
    * @access  public
    *
    */
    public function removeDirRecursive($directory)
    {
        if ($directory != '')
        {
            $files = $this->rawList($directory);
            $this->changeDir($directory);
            if (is_array($files))
            {
                for ($i = 0; $i < count($files); $i++)
                {
                    $fileInfo = $files[$i];
                    if ($fileInfo['type'] == 'dir')
                    {
                        $this->removeDirRecursive($fileInfo['name']);
                    }
                    else
                    {
                        $this->delete($fileInfo['name']);
                    }
                }
            }
            $this->changeDirUp();
            if($directory != './')
            {
                $this->removeDir($directory);
            }
        }
    }

    /**
    * Get the file list from the current directory
    *
    * @access  public
    *
    */
    public function &fileList($directory = '')
    {
        if (!$this->isConnected()) {
            return FALSE;
        } else {
            if ($directory != '') {
                list($changeDir, $fileMask) = $this->_parseDir($directory);
                if (!empty($changeDir)) {
                    $this->changeDir($changeDir);
                }
            } else {
                $fileMask = $directory;
            }
            $return = ftp_nlist($this->connectionId, $fileMask);
            if (!$return) {
                return FALSE;
            } else {
                return $return;
            }
        }
    }
    /**
    * Get the full infomation of file list from diectory
    *
    * @access  public
    *
    */
    public function rawList($directory = '', $parseInfo = TRUE)
    {
        if (!$this->isConnected())
        {
            return FALSE;
        }
        else {
            if ($directory != '') {
                list($changeDir, $fileMask) = $this->_parseDir($directory);
                if (!empty($changeDir)) {
                    $this->changeDir($changeDir);
                }
            }
            else
            {
                $fileMask = $directory;
            }

            $return = ftp_rawlist($this->connectionId, $fileMask);
            if (!$return)
            {
                return FALSE;
            }
            else
            {
                if ($parseInfo) {
                    $return = $this->_parseRawList($return);
                }
                return $return;
            }
        }
    }

    /**
    * download the remote file
    *
    * @access  public
    *
    */
    public function get($localFile, $remoteFile, $mode = NULL)
    {
        try
        {
            if (!$this->isConnected())
            {
                return FALSE;
            }
            else
            {
                //            list($changeDir, $remoteFile) = $this->_parseDir($remoteFile);
                //            echo "changeDir:{$changeDir},localFile:{$localFile},remoteFile:{$remoteFile}\n";
                //            if (!empty($changeDir)) $this->changeDir($changeDir);
                if (is_null($mode) || !in_array($mode, array(FTP_ASCII, FTP_BINARY))){
                    $mode = $this->transferMode;
                }

                $return = @ftp_get($this->connectionId, $localFile, $remoteFile, $mode);
                if ($return != FTP_FINISHED)
                {
                    return FALSE;
                }
                else
                {
                    return TRUE;
                }
            }
        }
        catch(Exception $e)
        {
            trigger_error("error when get",E_USER_ERROR);
            $this->close();
        }
    }
    /**
    * Get file
    *
    * @access  public
    *
    */
    public function fileGet($filePointer, $remoteFile, $mode = NULL)
    {
        if (!$this->isConnected())
        {
            return FALSE;
        }
        else if (!is_resource($filePointer))
        {
            trigger_error("Error: invalid resource.",E_USER_ERROR);

        }
        else
        {
            list($changeDir, $remoteFile) = $this->_parseDir($remoteFile);
            if (!empty($changeDir)) $this->changeDir($changeDir);
            if (is_null($mode) || !in_array($mode, array(FTP_ASCII, FTP_BINARY))) $mode = &$this->transferMode;
            $return = @ftp_fget($this->connectionId, $filePointer, $remoteFile, $mode);
            if ($return != FTP_FINISHED)
            {
                return FALSE;
            } else {
                return TRUE;
            }
        }
    }

    /**
    * Download multi files
    *
    * @access  public
    *
    */
    public function nGet($directory = '', $mode = NULL)
    {
        if (!$this->isConnected()) {
            return FALSE;
        }
        else {
            try
            {
                $list = $this->rawList($directory);
                if (!$list || !is_array($list)) return FALSE;

                foreach($list as $file) {
                    switch ($file['type'])
                    {
                        case 'dir' :
                            if (!@mkdir($file['name'])) {
                                continue;
                            }
                            chdir($file['name']);
                            $this->changeDir($file['name']);
                            $this->nGet('', $mode);
                            chdir('../');
                            $this->changeDirUp();
                            break;

                        case 'file' :
                            $this->get($file['name'], $file['name'], $mode);
                            break;
                        default : continue;
                        }
                    }
                }
                catch(Exception $e)
                {
                    trigger_error("error when nget",E_USER_ERROR);
                    $this->close();
                }
            }
        }
    /**
    * UpLoad the single file
    *
    * @access  public
    *
    */

        public function put($localFile, $remoteFile, $mode = null)
        {
            if (!$this->isConnected()) {
                return FALSE;
            } else {
                //                 list($changeDir, $remoteFile) = $this->_parseDir($remoteFile);
                //                if (!empty($changeDir)) $this->changeDir($changeDir);
                //                if (is_null($mode) || !in_array($mode, array(FTP_ASCII, FTP_BINARY))) $mode = $this->transferMode;
                return @ftp_put($this->connectionId, $localFile, $remoteFile, $mode);
            }
        }
    /**
    * Upload files
    *
    * @access  public
    *
    */

        public function filePut($filePointer, $remoteFile, $mode = null)
        {
            if (!$this->isConnected()) {
                return FALSE;
            } else if (!is_resource($filePointer)) {
                trigger_error("Error: invalid resource in filePut method.",E_USER_ERROR);

            } else {
                list($changeDir, $remoteFile) = $this->_parseDir($remoteFile);
                if (!empty($changeDir)) $this->changeDir($changeDir);
                if (is_null($mode) || !in_array($mode, array(FTP_ASCII, FTP_BINARY))) $mode = &$this->transferMode;
                return @ftp_fput($this->connectionId, $remoteFile, $filePointer, $mode);
            }
        }

    /**
    * Upload multiple files
    *
    * @access  public
    *
    */

        public function nPut($directory = '', $mode = null)
        {
            if (!$this->isConnected()) {
                return FALSE;
            }
            else
            {
                try
                {
                    if ($directory != '')
                    {
                        if (!is_dir($directory))
                        {
                            return FALSE;
                        }
                        else
                        {
                            chdir($directory);
                        }
                    }

                    $handle = opendir(getcwd());
                    if ($handle)
                    {
                        while (FALSE !== ($fileName = readdir($handle)))
                        {
                            if ($fileName != "." && $fileName != ".." && $fileName != ".svn")
                            {
                                if (is_dir($fileName))
                                {
                                    chdir($fileName);
                                    if (!@$this->makeDir($fileName, TRUE))
                                    {
                                        ;
                                    }
                                    $this->nPut('', $mode);
                                    chdir('..');
                                    $this->changeDirUp();
                                }
                                elseif (is_file($fileName))
                                {
                                    //                                    $this->delete($fileName);
                                    $this->put($fileName, $fileName, $mode);
                                }
                                else continue;
                            }
                        }
                        closedir($handle);
                    }
                }
                catch(Exception $e)
                {
                    trigger_error("error when nput",E_USER_ERROR);
                    $this->close();
                }
            }
        }

    /**
    * Delete files
    *
    * @access  public
    *
    */
        public function delete($remoteFile)
        {
            if (!$this->isConnected())
            {
                return FALSE;
            }
            else
            {
                return @ftp_delete($this->connectionId, $remoteFile);
            }
        }

    /**
    * Rename romote file
    *
    * @access  public
    *
    */
        public function rename($remoteFile, $newName)
        {
            if (!$this->isConnected()) {
                return FALSE;
            } else {
                list($changeDir, $remoteFile) = $this->_parseDir($remoteFile);
                if (!empty($changeDir)) $this->changeDir($changeDir);
                return @ftp_rename($this->connectionId, $remoteFile, $newName);
            }
        }

    /**
    * Get file last mode
    *
    * @access  public
    *
    */
        public function fileLastMod($remoteFile, $formatDate = TRUE)
        {
            if (!$this->isConnected()) {
                return FALSE;
            } else {
                list($changeDir, $remoteFile) = $this->_parseDir($remoteFile);
                if (!empty($changeDir)) $this->changeDir($changeDir);
                $return = @ftp_mdtm($this->connectionId, $remoteFile);
                if (!$return || $return == -1) {
                    return FALSE;
                } else {
                    if ($formatDate) {
                        $dateF = "d/m/Y";
                        $return = ($dateF == 'Y/m/d') ? date("$dateF H:i:s") : date("d/m/Y H:i:s");
                    }
                    return $return;
                }
            }
        }
    /**
    * Get file size
    *
    * @access  public
    *
    */
        public function fileSize($remoteFile)
        {
            if (!$this->isConnected()) {
                return FALSE;
            } else {
                list($changeDir, $remoteFile) = $this->_parseDir($remoteFile);
                if (!empty($changeDir)) $this->changeDir($changeDir);
                $return = @ftp_size($this->connectionId, $remoteFile);
                if (!$return || $return == -1) {
                    return FALSE;
                } else {
                    return $return;
                }
            }
        }

    /**
    * Parse directory
    *
    * @access  private
    *
    */
        public function _parseDir($str)
        {
            $slashPos = strrpos($str, '/');
            if ($slashPos>0)
            {
                return array(substr($str, 0, $slashPos + 1), substr($str, $slashPos + 1, strlen($str) - $slashPos));
            }
            else
            {
                return array('', $str);
            }
        }
    /**
    * parse raw file list
    *
    * @access  private
    *
    */

        public function _parseRawList($rawList)
        {
            if (is_array($rawList)) {
                $newList = array();
                while (list($k) = each($rawList)) {
                    $element = split(' {1,}', $rawList[$k], 9);
                    if (is_array($element) && (sizeOf($element) == 9)) {
                        unset($fileInfo);
                        $dateF = "d/m/Y";
                        $year = (FALSE !== strpos($element[7], ':')) ? $element[7] : date('Y');
                        $month = $element[5];
                        $day = (strlen($element[6]) == 2) ? $element[6] : '0' . $element[6];

                        $fileInfo['name'] = $element[8];
                        $fileInfo['size'] = intval($element[4]);
                        $fileInfo['date'] = ($dateF == 'Y/m/d') ? $year . '/' . $month . '/' . $day : $day . '/' . $month . '/' . $year;
                        $fileInfo['attr'] = $element[0];
                        $fileInfo['type'] = ($element[0][0] == '-') ? 'file' : 'dir';
                        $fileInfo['dirno'] = intval($element[1]);
                        $fileInfo['user'] = $element[2];
                        $fileInfo['group'] = $element[3];
                        $newList[] = $fileInfo;
                    }
                }
                return $newList;
            }
            return FALSE;
        }

        public function close()
        {
            if ($this->isConnected())
            {
                $this->connected = false;
                return @ftp_close($this->connectionId);
            }
            return true;
        }
    }
?>
Return current item: nfFTP