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

In-depth explanation of PHP FTP class_PHP tutorial

Jul 21, 2016 pm 03:06 PM
ftp php transmission protocol it support document Way yes model go deep of kind Detailed explanation

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles