Home  >  Article  >  Backend Development  >  In-depth explanation of PHP FTP class_PHP tutorial

In-depth explanation of PHP FTP class_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:06:20923browse

FTP is a file transfer protocol that supports two modes, one is called Standard (that is, Active mode), and the other is Passive (that is, PASV, is passive mode). The Standard mode FTP client sends the PORT command to the FTP server. Passive mode FTP client sends PASV command to FTP Server.
The following is an introduction to the working principles of these two methods:

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

Passive mode
is similar to Standard mode when establishing a control channel. When the client sends the PASV command through this channel, the FTP server opens a file located at 1024 and A random port between 5000 and notify the client of the request to transmit data on this port. Then the FTP server will transmit the data through this port. At this time, the FTP server no longer needs to establish a new connection with the client. connection.
Using PHP to operate FTP-usage

Copy code The code is as follows:

// Connect to FTP server
$conn = ftp_connect(ftp.server.com);

// Log in using username and password
ftp_login( $conn, “john”, “doe”);

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

// List files
$filelist = ftp_nlist($conn, “.”);

// Download file
ftp_get($conn, “data.zip”, “data.zip”, FTP_BINARY);

// Close the connection
ftp_quit($conn);

// Initialize an FTP connection. PHP provides the ftp_connect() function, which uses 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 the connection is successful, ftp_connect() returns a handle handle; this handle will be used by the FTP function used later.
$conn = ftp_connect(ftp.server.com);

//Once the connection is established, use ftp_login() to send a username and user password. You can see that the function ftp_login() uses the handle passed in the ftp_connect() function to determine that the username and password can be submitted to the correct server.
ftp_login($conn, “john”, “doe”);

// close connection
ftp_quit($conn);

//Logged in to the FTP server, PHP Provides functions that can obtain some information about the system and files and directories.
ftp_pwd()

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

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

// Passive mode (PASV) switch, turn PASV on or off (1 means on)
ftp_pasv($conn, 1);

//Use the ftp_chdir() function to enter the directory, which accepts a directory name as a parameter.
ftp_chdir($conn, “public_html”);

// Return to the parent directory of the current directory and use ftp_cdup() to implement it
ftp_cdup($conn);

// To create or move a directory, use the ftp_mkdir() and ftp_rmdir() functions; note: If ftp_mkdir() is successfully created, it will return the name of the newly created directory.
ftp_mkdir($conn, “test”);

ftp_rmdir($conn, “test”);

//Upload files, the ftp_put() function is very capable. It requires you to specify a local file name, the uploaded file name and the type of transfer. For example: If you want to upload the file "abc.txt" and name it "xyz.txt" after uploading, the command should be like this:
ftp_put($conn, "xyz.txt", "abc.txt", FTP_ASCII);

//Download file: The function provided by PHP is ftp_get(), which also requires a file name on the server, the file name after downloading, and the transmission type as parameters, for example: server-side file For his.zip, you want to download it to the local machine and name it hers.zip. The command is as follows:
ftp_get($conn, “hers.zip”, “his.zip”, FTP_BINARY);

//PHP provides two methods: one is to simply list the file name and directory, and the other is to list the file size, permissions, creation time and other information in detail.

//The first one uses the ftp_nlist() function, and the second one uses ftp_rawlist(). Both functions require a directory name as a parameter, and both return the directory column as an array. Each of the arrays An element is equivalent to a row of the list.
$filelist = ftp_nlist($conn, “.”);

//Function ftp_size(), which returns the size of the file you specify, using BITES as the unit. It should be pointed out that if it returns "-1", it means that this is a directory
$filelist = ftp_size($conn, "data.zip");

?>

FTP class
Copy code The code is as follows:

/**
* Imitate CodeIgniter's FTP class
* 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
*
* @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 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->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;
 }

 /**
* Directory change
*
* @access public
* @param string 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 generation
*
* @access public
* @param string Directory identification (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 identifier
* @param string Remote directory identifier (ftp)
* @param string Upload mode auto | | ascii
* @param int File permission list after uploading
* @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 identification (ftp)
* @param string local directory identification
* @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 identification (ftp)
* @param string New directory identification
* @param boolean Determination 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 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 identifier (ftp)
* @return boolean
*/
 public function delete_dir($path) {
  if( ! $this->_isconn()) {
   return FALSE;
  }

  //对目录宏的'/'字符添加反斜杠''
  $path = preg_replace("/(.+?)/*$/", "\1/", $path);

  //获取目录文件列表
  $filelist = $this->filelist($path);

  if($filelist !== FALSE AND count($filelist) > 0) {
   foreach($filelist as $item) {
    //如果我们无法删除,那么就可能是一个文件夹
    //所以我们递归调用delete_dir()
    if( ! @delete_file($item)) {
     $this->delete_dir($item);
    }
   }
  }

  //删除文件夹(空文件夹)
  $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 identifier (ftp)
* @return boolean
*/
 public function chmod($path, $perm) {
  if( ! $this->_isconn()) {
   return FALSE;
  }

  //只有在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 directory file list
*
* @access public
* @param string directory identifier (ftp)
* @return array
*/
 public function filelist($path = '.') {
  if( ! $this->_isconn()) {
   return FALSE;
  }

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

 /**
  * 关闭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 array
* @return void
*/
 private function _init($config = array()) {
  foreach($config as $key => $val) {
   if(isset($this->$key)) {
    $this->$key = $val;
   }
  }
  //特殊字符过滤
  $this->hostname = preg_replace('|.+?://|','',$this->hostname);
 }

 /**
  * FTP登陆
  *
  * @access  private
  * @return boolean
 */
 private function _login() {
  return @ftp_login($this->conn_id, $this->username, $this->password);
 }

 /**
  * 判断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 identifier
* @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 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
复制代码 代码如下:

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*/

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/327631.htmlTechArticleFTP是一种文件传输协议,它支持两种模式,一种方式叫做Standard (也就是Active,主动方式),一种是 Passive (也就是PASV,被动方式)。 Standard模式 FT...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn