In-depth PHP FTP class in the detailed _php tips

Source: Internet
Author: User
Tags chmod ftp connection ftp login parent directory ftp client file permissions file transfer protocol ftp transfer

FTP is a file transfer protocol, it supports two modes, one is called standard (that is, active, active mode), one is passive (that is, PASV, passive mode). Standard mode FTP client sends PORT command to FTP server. Passive mode FTP client sends PASV command to FTP Server.
Here's how one of these two ways works:

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

Passive mode
When the control channel is established and the standard mode is similar, when the client sends the PASV command through this channel, FTP server opens a random port between 1024 and 5000 and notifies the client of the request to transmit data on the port, and then FTP Server will transfer data through this port, and the FTP server no longer needs to establish a new connection to the client.
Using PHP to manipulate ftp-usage

Copy Code code as follows:

?
Join an FTP server
$conn = Ftp_connect (ftp.server.com);

Log on using username and password
Ftp_login ($conn, "John", "Doe");

Get remote system type
Ftp_systype ($conn);

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

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

Close Join
Ftp_quit ($conn);

Initial knot an FTP join, PHP provides ftp_connect () This function, it uses the host name and port as parameters. In the example above, 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.

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

Once a 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 committed to the correct server.
Ftp_login ($conn, "John", "Doe");

Close connection
Ftp_quit ($conn);

Logged on to the FTP server, PHP provides functions that can get information about systems 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 on or off PASV (1 for Open)
FTP_PASV ($conn, 1);

Enter the directory with the Ftp_chdir () function, which accepts a directory name as an argument.
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 using the Ftp_mkdir () and Ftp_rmdir () functions; note: if Ftp_mkdir () is successful, it will return the newly created directory name.
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, uploaded 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 order should be this:
Ftp_put ($conn, "Xyz.txt", "Abc.txt", ftp_ascii);

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

PHP offers two methods: one is to simply list the file name and directory, and the other is to specify the file size, permissions, time of creation, and so on.

The first type uses the Ftp_nlist () function, and the second uses the Ftp_rawlist (). Two functions require a directory name as a parameter, which returns a catalog column as an array, each of which corresponds to a row of the list.
$filelist = Ftp_nlist ($conn, ".");

function Ftp_size (), which returns the size of the file you specified, using bites as the unit. To point out, if it returns "-1", it means that this is a directory
$filelist = Ftp_size ($conn, "data.zip");

?>

FTP class
Copy Code code as follows:

<?php
/**
* Copy-write CodeIgniter FTP class
* FTP basic operation:
* 1) landing; Connect
* 2 List of current directory files; FileList
* 3) directory changes; Chgdir
* 4) renaming/moving; 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
*
* Array @param array: $config = array (' hostname ' => ', ' username ' => ', ' Password ' => ', ' Port ' => ' ...);
*/
Public function __construct ($config = Array ()) {
if (count ($config) > 0) {
$this->_init ($config);
}
}

/**
* FTP connection
*
* @access Public
* Array Configuration @param 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 identification (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;
}

/**
* Catalog Generation
*
* @access Public
* @param string Directory identification (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 identification
* @param string Remote directory identification (FTP)
* @param string upload mode auto | | Ascii
* @param int uploaded file permissions list
* @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 judge 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 identification (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 identification (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 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 identification (FTP)
* @return Boolean
*/
Public function chmod ($path, $perm) {
if (! $this->_isconn ()) {
return FALSE;
}

Functions that modify permissions are 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 directory file list
*
* @access Public
* @param string Directory identification (FTP)
* @return Array
*/
Public function filelist ($path = '. ') {
if (! $this->_isconn ()) {
return FALSE;
}

Return Ftp_nlist ($this->conn_id, $path);
}

/**
* Turn off 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
* Array Configuration @param array
* @return void
*/
Private Function _init ($config = Array ()) {
foreach ($config as $key => $val) {
if (Isset ($this-> $key)) {
$this-> $key = $val;
}
}
Special character Filter
$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 filename
*
* @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 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 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
Copy Code code as follows:

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

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.