Dive into the details of the PHP FTP class

  • 2020-06-15 07:51:56
  • OfStack

FTP is a file transfer protocol that supports two modes: Standard (active) and Passive (passive). The Standard mode FTP client sends the PORT command to FTP server. Passive mode FTP's client sends the PASV command to FTP Server.
Here's how they work:

Standard mode
The FTP client first establishes a connection with the TCP 21 port of FTP Server and sends commands through this channel, where the client sends PORT commands when it needs to receive data. The PORT command contains the port on which the client receives the data. When transmitting data, the server sends data through its own TCP 20 port. FTP server must establish a new connection with the client to transmit data.

Passive mode
At the time of establishing control channel and Standard pattern, when the client sent through this channel PASV command, FTP server open a random port lies between 1024 and 5000 and notify the client send data request on this port, then FTP server will be through the port for data transmission, this time FTP server between the client and no longer need to establish a new connection.
Use PHP to operate FTP- usage


<?  
    //  join FTP The server   
    $conn = ftp_connect(ftp.server.com);  

    //  use username and password The login   
    ftp_login($conn,  " john " ,  " doe " );  

    //  Gets the remote system type   
    ftp_systype($conn);  

    //  List the files   
    $filelist = ftp_nlist($conn,  " . " );  

    //  The download file   
    ftp_get($conn,  " data.zip " ,  " data.zip " , FTP_BINARY);  

    //  Close connection   
    ftp_quit($conn);  

    // At the beginning of knot, 1 a FTP Join, PHP provides ftp_connect() This function takes the host name and port as parameters. In the above example, the host name is   " ftp.server.com "; If the port is not specified, PHP Will use" 21 "As the default port to establish the connection.   

    // After successful connection ftp_connect() Back to the 1 a handle Handle; this handle Will be used later FTP Function use.   
    $conn = ftp_connect(ftp.server.com);  

    //1 Once the connection is established, use it ftp_login() send 1 User name and password. You can see the function ftp_login() Using the  ftp_connect() From the function handle To ensure that the username and password can be submitted to the correct server.   
    ftp_login($conn,  " john " ,  " doe " );  

    // close connection  
    ftp_quit($conn);  

    // Log on to the FTP The server, PHP provides 1 Some functions, they can get 1 Some information about the system and files and directories.   
    ftp_pwd()  

    // Gets the current directory   
    $here = ftp_pwd($conn);  

    // Gets server side system information ftp_systype()  
    $server_os = ftp_systype($conn);  

    // Passive mode ( PASV ), on or off PASV ( 1 Said)   
    ftp_pasv($conn, 1);  

    // Go into the directory ftp_chdir() The delta function, it accepts 1 Five directory names as parameters.   
    ftp_chdir($conn,  " public_html " );  

    // Go back to the parent directory ftp_cdup() implementation   
    ftp_cdup($conn);  

    // Create or move 1 This is going to be used ftp_mkdir() and ftp_rmdir() Functions; Note: ftp_mkdir() On success, the newly created directory name will be returned.   
    ftp_mkdir($conn,  " test " );  

    ftp_rmdir($conn,  " test " );  

    // Upload the file, ftp_put() The function does a good job, it needs to be specified 1 The local file name, the uploaded file name, and the type of transfer. For example: If you want to upload   " abc.txt "This file, when uploaded, is called" xyz.txt "The order should be this:   
    ftp_put($conn,  " xyz.txt " ,  " abc.txt " , FTP_ASCII);  

    // Download files: PHP The provided function is ftp_get() It also needs 1 File name on server, file name after download, and transfer type as parameters, such as: server side file is his.zip , you want to download to the local machine and name it as hers.zip , the command is as follows:   
    ftp_get($conn,  " hers.zip " ,  " his.zip " , FTP_BINARY);  

    //PHP There are two ways: 1 The kind is simply listing file names and directories, as well 1 A type is a detailed list of file size, permissions, creation time, and other information.   

    // The first 1 Kind of use ftp_nlist() Function, the first 2 with ftp_rawlist(). Both functions are required 1 Each of the directory names is returned as a directory column 1 An array, each of the arrays 1 The elements are equivalent to a list 1 Line.   
    $filelist = ftp_nlist($conn,  " . " );  

    // function ftp_size() , it returns the size of the file you specified, using the BITES As a unit. And the point is, if it returns is   " -1 "Means that it is 1 A directory   
    $filelist = ftp_size($conn,  " data.zip " );  

    ?>  

FTP class

<?php
/**
 *  Copy write CodeIgniter the FTP class 
 * FTP Basic operation: 
 * 1)  landing ;    connect
 * 2)  List of current directory files ;  filelist
 * 3)  Change directory ;   chgdir
 * 4)  rename / mobile ;  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;

 /**
  *  The constructor 
  *
  * @param array  Configuration of array  : $config = array('hostname'=>'','username'=>'','password'=>'','port'=>''...);
  */
 public function __construct($config = array()) {
  if(count($config) > 0) {
   $this->_init($config);
  }
 }

 /**
  * FTP The connection 
  *
  * @access  public
  * @param  array   Configuration of 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;
 }

 /**
  *  Change directory 
  *
  * @access  public
  * @param  string   The directory identifier (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 to generate 
  *
  * @access  public
  * @param  string   The directory identifier (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 id 
  * @param string  Remote directory id (ftp)
  * @param string  Upload the model  auto || ascii
  * @param int   List of uploaded file permissions  
  * @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 id (ftp)
  * @param string  Local directory id 
  * @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 / mobile 
  *
  * @access  public
  * @param  string   Remote directory id (ftp)
  * @param string  New directory id 
  * @param boolean  The judgment is to rename (FALSE) Or mobile (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   The directory identifier (ftp)
  * @return boolean
  */
 public function delete_dir($path) {
  if( ! $this->_isconn()) {
   return FALSE;
  }

  // For the directory macro '/' Add backslashes for characters '\'
  $path = preg_replace("/(.+?)\/*$/", "\\1/", $path);

  // Gets a list of directory files 
  $filelist = $this->filelist($path);

  if($filelist !== FALSE AND count($filelist) > 0) {
   foreach($filelist as $item) {
    // If we can't delete it , So it could be 1 A folder 
    // So we call it recursively delete_dir()
    if( ! @delete_file($item)) {
     $this->delete_dir($item);
    }
   }
  }

  // Delete folder ( An 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   The directory identifier (ftp)
  * @return boolean
  */
 public function chmod($path, $perm) {
  if( ! $this->_isconn()) {
   return FALSE;
  }

  // Only in the PHP5 Functions that modify permissions are defined in (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;
 }

 /**
  *  Gets a list of directory files 
  *
  * @access  public
  * @param  string   The directory identifier (ftp)
  * @return array
  */
 public function filelist($path = '.') {
  if( ! $this->_isconn()) {
   return FALSE;
  }

  return ftp_nlist($this->conn_id, $path);
 }

 /**
  *  Shut down 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 of 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 landing 
  *
  * @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;
 }

 /**
  *  Gets the suffix extension from the file name 
  *
  * @access  private
  * @param  string   The directory identifier 
  * @return string
  */
 private function _getext($filename) {
  if(FALSE === strpos($filename, '.')) {
   return 'txt';
  }

  $extarr = explode('.', $filename);
  return end($extarr);
 }

 /**
  *  Extend the definition from the suffix FTP Transfer mode   ascii  or  binary
  *
  * @access  private
  * @param  string   The 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  prvate
  * @return boolean
  */
 private function _error($msg) {
  return @file_put_contents('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*/

DEMO

<?php
require_once('ftp.php');
$config = array(
   'hostname' => 'localhost',
   'username' => 'root',
   'password' => 'root',
   'port' => 21
    );
$ftp = new Ftp();
$ftp->connect($config);
$ftp->upload('ftp_err.log','ftp_upload.log');
$ftp->download('ftp_upload.log','ftp_download.log');
/*End of file ftp_demo.php*/
/*Location: /htdocs/ftp_demo.php*/


Related articles: