PHP ftp FTP upload file script

Source: Internet
Author: User
Tags ftp connection ftp login ftp upload file rtrim upload php ftp transfer

Why use this class?

Because of an egg ache project, Project Server in another company (referred to as company A) hands, company A, their servers do not open the network permissions, afraid of problems. Because the project is under development, so often need to upload PHP code to the server, because no permissions, so the upload code using the efficiency Super slow manual upload-_-, in my repeated request, finally opened a springboard machine ftp, each upload code to this FTP, and then company A, Automatically synchronizes the code inside the FTP to the corresponding server.

Then, the problem again, FTP only for the designated IP customers open, and then the workplace of the public IP is constantly changing, so helpless, this IP point to a test Linux operating system server.

Then, the problem continues to come, because the server does not have a GUI interface, FTP only support command line, perform multiple upload operations, that process, who who knows, so in this helpless, produced the following this class, with PHP to control a button upload.

Approximate principle

  • Traverse all non-excluded files in the project, and then get files that are modified later than the last modification time of the file
  • These files are then uploaded to the corresponding directory via FTP
  • The specific code is as follows:

    Because it's just a tool, the code is messy, forgive me

    Php
     Zip ($path); Filter out the latest modification files $path = str_replace ("/data/longtu/", "" ", $path); $config = array (' hostname ' = ' xxx.xxx.xx.xxx ',//ftp Server address ' username ' + ' xxx ',//ftp user ' password ' = '? xxxxxxxxxxx ',//ftp password ' port ' =&G T                21//port); $ftp = new FTP (); $ftp->connect ($config); Linked server//$a = $ftp->filelist (); $LOCAL _root = Realpath (dirname (__dir__). " /.. /..      /"); ChDir ($LOCAL _root), foreach ($files as $k = = $v) {$f = $path. $v;      $tmp = $ftp->upload ($f, $f);      if ($tmp) {echo "upload $f, success \ n"; }}//$ftp->download (' Ftp_upload.log ', ' ftp_download.log ');////$ftp->upload (' Ftp_err.log ', ' Ftp_upload.log ')    ;//$ftp->download (' Ftp_upload.log ', ' ftp_download.log ');/* * * * $dir = "/test"; if (@ftp_chdir ($conn, $dir)) Determine if it is a folder * Enter description here ... * @author Administrator * */class filerfile{var    $time _path;    Private $fctimes = Array (); function Zip ($dir) {$this->time_path = RTrim ($dir, "/"). "        /.~~~time.php ";        @unlink ($this->time_path);        $filelist = $this-Getfilelist ($dir); File_put_contents ($this->time_path, "
     fctimes,true). ";");    return $filelist;        } function Appendfilectime ($file) {$time _file_path = $this->time_path;        $ftime = @include ($time _file_path); $ftime = $ftime?        $ftime: Array ();        $time = Filectime ($file); if (!file_exists ($time _file_path)) file_put_contents ($time _file_path, "
     Time_path;        if (! $time _data) {$time _data= @include_once ($time _file_path); } $time _data = $time _data?        $time _data:array ();        Var_dump ($file, $time _data[$file] = = Filectime ($file)); echo $file. " \ t ". $time _data[$file]."        \ n ";        if ($time _data[$file] = = Filemtime ($file)) {return false;        }else{return $file;        }} function Getfilelist ($dir, $path = "") {Static $tmpp = "";        if ($path = = "" &&! $tmpp) {$tmpp = $dir;        } $d = Dir ($dir);        $files = Array ();            if ($d) {$pathP =str_replace ($tmpp, "", $dir);            $pathP =str_replace (Array ("\\\\", "/"), Directory_separator, $pathP); $pathP =str_replace (directory_separator.            Directory_separator,directory_separator, $pathP); while ($f = $d->read ()) {if ($f = = ') ' | | $f = = '.. ' | | $f {0}== '. ' | | $f = = ' Zend ' | | in_array ($f  , $_get[' exclude ')) continue;              $newdir = RTrim ($dir, "/"). "                /". $f;                if (Is_dir ($newdir)) {$files = Array_merge ($files, $this->getfilelist ($newdir, $newdir)); }else{$abspath _file = (RTrim ($dir, "/")? RTrim ($dir, "/"). "                    /":"). $f;                    $this->fctimes[$abspath _file] = filemtime ($abspath _file);                    if (! $this->getfilebyfilectime ($abspath _file)) continue; $file = (RTrim ($pathP, "/")? RTrim ($pathP, "/"). "                    /":"). $f;                $files [] = $file;    }}} return $files;           }}/** * Copy CodeIgniter FTP class * FTP basic operation: * 1) login;  Connect * 2) List of current directory files;         FileList * 3) directory changes;       Chgdir * 4) rename/move;        Rename * 5) Create folder;               mkdir * 6) Delete;               Delete_dir/delete_file * 7) upload;    Upload * 8) Download Download * * @author Quanshuidingdang */class Ftp {private $hostname = ';    Private $username = '; PriVate $password = ";    Private $port = 21;    Private $passive = TRUE;    Private $debug = TRUE;    Private $conn _id = FALSE; /** * Constructor * * @param array configuration arrays: $config = array (' hostname ' = ' = ', ' username ' = ' = ', ' password ' = = ', '     Port ' = = ' ...); */Public Function __construct ($config = Array ()) {if (count ($config) > 0) {$this->_init ($conf        IG); }}/** * FTP connection * * @access public * @param array Configuration Array * @return Boolean */Public        Function Connect ($config = Array ()) {if (count ($config) > 0) {$this->_init ($config); if (FALSE = = = ($this->conn_id = @ftp_connect ($this->hostname, $this->port))) {if ($this->deb            UG = = TRUE) {$this->_error ("Ftp_unable_to_connect");        } return FALSE;                } if (! $this->_login ()) {if ($this->debug = = = TRUE) {$this->_error ("Ftp_unable_to_login");        } return FALSE;        } if ($this->passive = = = True) {FTP_PASV ($this->conn_id, true);    } return TRUE; }/** * Folder exists * @param unknown_type $path */Public Function is_dir_exists ($path) {return $    This->chgdir ($path); }/** * Directory changed * * @access public * @param string directory ID (FTP) * @param boolean * @return bo Olean */Public Function chgdir ($path = ", $supress _DEBUG = FALSE) {if ($path = =" OR! $this->_isconn (        ) {return FALSE;        } $result = @ftp_chdir ($this->conn_id, $path); if ($result = = = False) {if ($this->debug = = = TRUE and $supress _DEBUG = = False) {$this->_er            Ror ("ftp_unable_to_chgdir:dir[". $path. "]");        } return FALSE;    } return TRUE; }/** * Directory generation * * @access public * @param sTring Directory Identity (FTP) * @param int file permission list * @return Boolean */Public function mkdir ($path = ", $permi        Ssions = NULL) {if ($path = = ' OR! $this->_isconn ()) {return FALSE;        } $result = @ftp_mkdir ($this->conn_id, $path); if ($result = = = FALSE) {if ($this->debug = = = TRUE) {$this->_error ("Ftp_unable_to_mkdir:dir            [". $path."] ");        return FALSE;        } if (! Is_null ($permissions)) {$this->chmod ($path, (int) $permissions);    } return TRUE; }/** * Upload * * @access public * @param string Local Directory Identity * @param string remote directory Identity (FTP) * @para M string upload Mode auto | |  ASCII * @param int uploaded file permission list * @return Boolean */Public function upload ($localpath, $remotepath,        $mode = ' Auto ', $permissions = NULL) {if (! $this->_isconn ()) {return FALSE; } if (! file_exists ($locAlpath) {if ($this->debug = = = TRUE) {$this->_error ("Ftp_no_source_file:". $localpath);        } return FALSE;            } if ($mode = = ' auto ') {$ext = $this->_getext ($localpath);        $mode = $this->_settype ($ext); } $mode = ($mode = = = ' ASCII ')?        Ftp_ascii:ftp_binary;        $result = @ftp_put ($this->conn_id, $remotepath, $localpath, $mode); if ($result = = = FALSE) {if ($this->debug = = = TRUE) {$this->_error ("Ftp_unable_to_upload:lo Calpath[". $localpath."]            /remotepath[". $remotepath."] ");        return FALSE;        } if (! Is_null ($permissions)) {$this->chmod ($remotepath, (int) $permissions);    } return TRUE; }/** * Download * * @access public * @param string remote directory Identification (FTP) * @param string Local directory identifier * @para M string Download Mode Auto | | ASCII * @return Boolean */Public function Download ($remotepath, $localpath, $mode = ' auto ') {if (! $this->_isconn ()) {return FALSE;            } if ($mode = = ' auto ') {$ext = $this->_getext ($remotepath);        $mode = $this->_settype ($ext); } $mode = ($mode = = = ' ASCII ')?        Ftp_ascii:ftp_binary;        $result = @ftp_get ($this->conn_id, $localpath, $remotepath, $mode); if ($result = = = FALSE) {if ($this->debug = = = TRUE) {$this->_error ("Ftp_unable_to_download: Localpath[". $localpath."]            -remotepath[". $remotepath."] ");        return FALSE;    } return TRUE; }/** * Rename/move * * @access public * @param string remote directory Identity (FTP) * @param string new directory ID * @p Aram Boolean determines whether to rename (FALSE) or Move (TRUE) * @return Boolean */Public Function rename ($oldname, $newname, $move        = False) {if (! $this->_isconn ()) {return false; } $result = @ftp_renAme ($this->conn_id, $oldname, $newname); if ($result = = = False) {if ($this->debug = = = TRUE) {$msg = ($move = = False)?                "Ftp_unable_to_rename": "Ftp_unable_to_move";            $this->_error ($msg);        } return FALSE;    } return TRUE; }/** * Delete file * * @access public * @param string file ID (FTP) * @return Boolean */public F        Unction Delete_file ($file) {if (! $this->_isconn ()) {return FALSE;        } $result = @ftp_delete ($this->conn_id, $file); if ($result = = = FALSE) {if ($this->debug = = = TRUE) {$this->_error ("Ftp_unable_to_delete_fi            Le:file[". $file."] ");        return FALSE;    } return TRUE; }/** * Delete folder * * @access public * @param string directory ID (FTP) * @return Boolean */Public  function Delete_dir ($path) {if (! $this->_isconn ()) {          return FALSE; }//Add backslash ' \ ' to the '/' character of the directory macro $path = Preg_replace ("/(. +?)        \/*$/"," \\1/", $path);        Get list of directory files $filelist = $this->filelist ($path); if ($filelist!== FALSE and Count ($filelist) > 0) {foreach ($filelist as $item) {//If we cannot delete, then It could be a folder//So we recursively call Delete_dir () if (! @delete_file ($item)) {$this-                Delete_dir ($item);        }}}//Delete folder (empty folder) $result = @ftp_rmdir ($this->conn_id, $path); if ($result = = = FALSE) {if ($this->debug = = = TRUE) {$this->_error ("Ftp_unable_to_delete_di            R:dir[". $path."] ");        return FALSE;    } return TRUE;  }/** * Modify file Permissions * * @access public * @param string directory ID (FTP) * @return Boolean */Public function chmod ($path, $perm) {if (! $this->_isconn ()) {return falsE                 The function (FTP) if (! function_exists (' Ftp_chmod ')) {if ($this->debug = = = TRUE) {if}//is defined only in PHP5) {            $this->_error ("Ftp_unable_to_chmod (function)");        } return FALSE;        } $result = @ftp_chmod ($this->conn_id, $perm, $path); if ($result = = = FALSE) {if ($this->debug = = = TRUE) {$this->_error ("Ftp_unable_to_chmod:pat H[". $path."]            -chmod[". $perm."] ");        return FALSE;    } return TRUE;  /** * Get directory file list * * @access public * @param string directory ID (FTP) * @return Array */public function filelist ($path = '. ')        {if (! $this->_isconn ()) {return FALSE;    } return Ftp_nlist ($this->conn_id, $path); }/** * Close FTP * * @access Public * @return Boolean */Public function close () {if (! $        This->_isconn ()) {return FALSE;   }     Return @ftp_close ($this->conn_id); }/** * FTP member variable initialization * * @access private * @param array configuration arrays * @return void */priv Ate function _init ($config = Array ()) {foreach ($config as $key + $val) {if (Isset ($this $key))            {$this $key = $val; }}//special character filter $this->hostname = preg_replace (' |. +?:/    /| ', ', $this->hostname); /** * FTP Login * * @access Private * @return Boolean */Private Function _login () {Retu    RN @ftp_login ($this->conn_id, $this->username, $this->password);        }/** * Judge con_id * * @access Private * @return Boolean */Private Function _isconn () { if (! Is_resource ($this->conn_id)) {if ($this->debug = = = TRUE) {$this->_error ("Ftp_no_            Connection ");        } return FALSE;    } return TRUE; }/** * Get suffix extension from file name     * * @access Private * @param string directory identifier * @return String */Private function _getext ($filena Me) {if (FALSE = = = Strpos ($filename, '. '))        {return ' txt ';        } $extarr = Explode ('. ', $filename);    Return end ($extarr); }/** * Defines the FTP transfer mode from the suffix extension ASCII or binary * * @access private * @param string suffix extension * @return stri                            NG */Private Function _settype ($ext) {$text _type = array (' txt ', ' Text ', ' php ', ' Phps ', ' PHP                            4 ', ' JS ', ' css ', ' htm ', ' HTML ', ' phtml ', ' shtml ', ' log '        , ' xml '); Return (In_array ($ext, $text _type))? ' ASCII ': ' binary ';        }/** * ERROR log record * * @access prvate * @return Boolean */Private Function _error ($msg) { Return @file_put_contents ('/tmp/ftp_err.log ', "date[". Date ("Y-m-d h:i:s"). "] -hostname[". $this->hostname."] -username[". $this->username."] -password[". $this->password."] -msg[". $msg."]    \ n ", file_append); }}/*end of File Ftp.php*//*location/apache group/htdocs/ftp.php*/
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.