In-depth PHP FTP class _php Tutorial

Source: Internet
Author: User
Tags ftp connection ftp login ftp client file transfer protocol ftp transfer
FTP is a file transfer protocol, it supports two modes, one is called standard (that is, active, active), one is Passive (that is, PASV, passive mode). The standard mode FTP client sends the PORT command to the FTP server. The passive mode FTP client sends the PASV command to the FTP Server.
Here's how one of these two approaches works:

Standard mode
The FTP client first establishes a connection to the FTP server's TCP 21 port and sends a command through this channel, which sends the port command on this channel when the client needs to receive the data. The port command contains what ports the client uses to receive data. When transmitting data, the server sends the data through its own TCP 20 port. The FTP server must establish a new connection with the client to transfer the data.

Passive Mode
When establishing a control channel similar to standard mode, when the client sends the PASV command through this channel, the FTP server opens a random port between 1024 and 5000 and notifies the client of the request to transmit data on this port, and then the FTP server The data will be transferred through this port, and the FTP server no longer needs to establish a new and client connection.
using PHP to manipulate ftp-usage
Copy CodeThe code is as follows:
Join an FTP server
$conn = Ftp_connect (ftp.server.com);

Sign in with username and password
Ftp_login ($conn, "John", "Doe");

Get the remote system type
Ftp_systype ($conn);

Listing files
$filelist = Ftp_nlist ($conn, ".");

Download file
Ftp_get ($conn, "Data.zip", "Data.zip", ftp_binary);

Close Join
Ftp_quit ($conn);

Initially knot an FTP connection, PHP provides the Ftp_connect () function, which uses the host name and port as the parameter. In the above example, the host name is "Ftp.server.com", and if the port is not specified, PHP will use "21" as the default port to establish the join.

After the join succeeds, Ftp_connect () returns a handle handle, and the handle will be used by the FTP function that is used later.
$conn = Ftp_connect (ftp.server.com);

Once the join is established, use Ftp_login () to send a user name and user password. As you can see, this function Ftp_login () uses the handle from the Ftp_connect () function to determine that the user name and password can be submitted to the correct server.
Ftp_login ($conn, "John", "Doe");

Close connection
Ftp_quit ($conn);

Log in to the FTP server, PHP provides a number of functions, they can get some information about the system and files and directories.
Ftp_pwd ()

Get the directory that is currently located
$here = Ftp_pwd ($conn);

Get server-side System Information Ftp_systype ()
$server _os = Ftp_systype ($conn);

Switch in passive mode (PASV), turn PASV on or off (1 means on)
FTP_PASV ($conn, 1);

Enter the directory with the Ftp_chdir () function, which accepts a directory name as a parameter.
Ftp_chdir ($conn, "public_html");

Go back to the directory where the parent directory is implemented with Ftp_cdup ()
Ftp_cdup ($conn);

Create or move a directory that uses the Ftp_mkdir () and Ftp_rmdir () functions; note: if Ftp_mkdir () is successful, the newly created directory name will be returned.
Ftp_mkdir ($conn, "test");

Ftp_rmdir ($conn, "test");

Upload file, Ftp_put () function is very good, it requires you to specify a local file name, upload the file name and the type of transmission. For example: If you want to upload "abc.txt" This file, after uploading the name "Xyz.txt", the command should be this:
Ftp_put ($conn, "Xyz.txt", "Abc.txt", ftp_ascii);

Download file: PHP provides the function is Ftp_get (), it also needs a server file name, download the file name, as well as the transport type as parameters, for example: server-side file for His.zip, you want to download to the local machine, and named Hers.zip, the command is as follows:
Ftp_get ($conn, "Hers.zip", "His.zip", ftp_binary);

PHP offers two methods: one is to simply list file names and directories, and the other is to specify the size of files, permissions, creation time and other information.

The first one uses the Ftp_nlist () function, and the second uses ftp_rawlist (). Two functions require a directory name as a parameter, return the catalog column as an array, each element of the array 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. To point out is that if it returns "1", it means that this is a directory
$filelist = Ftp_size ($conn, "data.zip");

?>

FTP class
Copy CodeThe code is as follows:
 /**
* Copy-write CodeIgniter FTP class
* FTP basic operation:
* 1) landing; Connect
* 2) List of current directory files; FileList
* 3) directory changes; Chgdir
* 4) rename/move; Rename
* 5) Create a 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 function
*
* @param array configuration arrays: $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
* @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 identifier (FTP)
* @param int file permissions 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 identification (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 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 identification (FTP)
* @param string new directory ID
* @param Boolean to 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 Files
*
* @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;
}

Add backslash ' \ ' to the '/' character of the directory macro
$path = Preg_replace ("/(. +?) \/*$/"," \\1/", $path);

Get catalog File List
$filelist = $this->filelist ($path);

if ($filelist!== FALSE and Count ($filelist) > 0) {
foreach ($filelist as $item) {
If we can't delete it, 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_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;
}

A function (FTP) that modifies permissions is defined only in PHP5
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);
}

/**
* 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
* @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 ID
* @return String
*/
Private Function _getext ($filename) {
if (FALSE = = = Strpos ($filename, '. ')) {
return ' txt ';
}

$extarr = Explode ('. ', $filename);
Return end ($extarr);
}

/**
* Definition of FTP transfer mode ASCII or binary from suffix extension
*
* @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 log record
*
* @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
Copy CodeThe code is as follows:
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*/

http://www.bkjia.com/PHPjc/327631.html www.bkjia.com true http://www.bkjia.com/PHPjc/327631.html techarticle FTP is a file transfer protocol, it supports two modes, one is called standard (that is, active, active), one is Passive (that is, PASV, passive mode). Standard mode FT ...

  • Related Article

    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.