SoFunction
Updated on 2025-03-08

PHP implementation upload files through ftp

Probably the principle

Iterate through all non-excluded files in the project and get files whose file modification time is later than the last file modification time

Then upload these files to the corresponding directory through ftp

The specific code is as follows:

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

<?php
error_reporting(7);
if ($_SERVER['SERVER_ADDR'])exit;//Not running under the web server$_GET['exclude'] = array('','uploads','Zend','docs','cache','You','managesdk'); //Exclude upload directory and define it as a global variable$fileobj = new FilerFile();
$path = "/data/longtu/"; //The root directory of the project directory$files = $fileobj->Zip($path); //Filter out the latest modified files$path = str_replace("/data/longtu/","",$path);
$config = array(
  'hostname' => '', //ftp server address  'username' => 'xxx',     //ftp user  'password' => '?xxxxxxxxxxx', //ftp password  'port' => 21         //port);
$ftp = new Ftp();
$ftp->connect($config);       //Link 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 whether 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,"/")."/.~~~";
  //@unlink($this->time_path);
  $filelist = $this -> GetFileList($dir);
  file_put_contents($this->time_path,"<?php \n return ".var_export($this->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,"<?php \n");
 }
 function getFileByFilectime($file)
 {
  static $time_data ;
  $time_file_path = $this->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;
 }
}
/**
  * FTP class imitating CodeIgniter
  * Basic FTP operations:
  * 1) Log in; connect
  * 2) Current directory file list; filelist
  * 3) Directory change; 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 array: $config = array('hostname'=>'','username'=>'','password'=>'','port'=>''...);
   */
 public function __construct($config = array()) {
  if(count($config) > 0) {
   $this->_init($config);
  }
 }
 /**
   * FTP connection
   *
   * @access public
   * @param array Configure 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->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;
  }
  if($this->passive === TRUE) {
   ftp_pasv($this->conn_id, TRUE);
  }
  return TRUE;
 }
 /**
   * Whether the folder exists
   * @param unknown_type $path
   */
 public function is_dir_exists($path)
 {
  return $this->chgdir($path);
 }
 /**
   * Directory changes
   *
   * @access public
   * @param string directory identity (ftp)
   * @param boolean
   * @return boolean
   */
 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->_error("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 = '', $permissions = 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)
   * @param string Upload mode auto || ascii
   * @param int File permission list after upload
   * @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:localpath[".$localpath."]/remotepath[".$remotepath."]");
   }
   return FALSE;
  }
  if( ! is_null($permissions)) {
   $this->chmod($remotepath,(int)$permissions);
  }
  return TRUE;
 }
 /**
   * download
   *
   * @access public
   * @param string Remote directory identity (ftp)
   * @param string Local directory identity
   * @param 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 identity
   * @param boolean Determine 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 the file
   *
   * @access public
   * @param string file identifier (ftp)
   * @return boolean
   */
 public function 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_file:file[".$file."]");
   }
   return FALSE;
  }
  return TRUE;
 }
 /**
   * Delete folder
   *
   * @access public
   * @param string directory identity (ftp)
   * @return boolean
   */
 public function delete_dir($path) {
  if( ! $this->_isconn()) {
   return FALSE;
  }
  //Add a backslash to the '/' character of the directory macro  $path = preg_replace("/(.+?)\/*$/", "\\1/", $path);
   //Get the directory file list
   $filelist = $this->filelist($path);
   if($filelist !== FALSE AND count($filelist) > 0) {
    foreach($filelist as $item) {
     //If we cannot delete it, it may be a folder
     //So we call delete_dir() recursively
     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_dir:dir[".$path."]");
    }
    return FALSE;
   }
   return TRUE;
  }
  /**
   * Modify file permissions
   *
   * @access public
   * @param string directory identity (ftp)
   * @return boolean
   */
 public function chmod($path, $perm) {
  if( ! $this->_isconn()) {
   return FALSE;
  }
  //The function that modifies permissions is defined only in PHP5 (ftp)  if( ! function_exists('ftp_chmod')) {
   if($this->debug === TRUE) {
    $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:path[".$path."]-chmod[".$perm."]");
   }
   return FALSE;
  }
  return TRUE;
 }
 /**
   * Get the directory file list
   *
   * @access public
   * @param string directory identity (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 Configure array
   * @return void
   */
 private function _init($config = array()) {
  foreach($config as $key => $val) {
   if(isset($this->$key)) {
    $this->$key = $val;
   }
  }
  //Special character filtering  $this->hostname = preg_replace('|.+?://|','',$this->hostname);
 }
 /**
   * FTP login
   *
   * @access private
   * @return boolean
   */
 private function _login() {
  return @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 the suffix extension from the file name
   *
   * @access private
   * @param string directory identification
   * @return string
   */
 private function _getext($filename) {
  if(FALSE === strpos($filename, '.')) {
   return 'txt';
  }
  $extarr = explode('.', $filename);
  return end($extarr);
 }
 /**
   * Define FTP transfer mode from suffix extension ascii or binary
   *
   * @access private
   * @param string suffix extension
   * @return string
   */
 private function _settype($ext) {
  $text_type = array (
       'txt',
       'text',
       'php',
       'phps',
       'php4',
       'js',
       'css',
       'htm',
       'html',
       'phtml',
       'shtml',
       'log',
       'xml'
       );
  return (in_array($ext, $text_type)) ? 'ascii' : 'binary';
 }
 /**
   * Error logging
   *
   * @access purchase
   * @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 */
/*Location /Apache Group/htdocs/*/

The above is the entire content of this article, I hope you like it.