In-depth explanation of the php ftp class

Source: Internet
Author: User
Tags ftp connection ftp login ftp client file transfer protocol

FTP is a File Transfer Protocol that supports two modes: Standard (Active) and Passive (PASV, passive mode ). The FTP client in Standard mode sends the PORT command to the FTP server. The client in Passive mode sends the PASV command to the FTP Server.
The following describes how these two methods work:

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

Passive Mode
When establishing a control channel, it is similar to the Standard mode. When the client sends the PASV command through this channel, the FTP server opens a random port between port 1024 and port 5000 and notifies the client to send data requests on this port. Then, the FTP server transfers data through this port, at this time, the FTP server no longer needs to establish a new connection with the client.
Use PHP to operate FTP-usage

Copy codeThe Code is as follows: <?
// Connect to the FTP server
$ Conn = ftp_connect (ftp.server.com );

// Use username and password to log on
Ftp_login ($ conn, "john", "doe ");

// Obtain the remote system type
Ftp_cmdype ($ conn );

// List objects
$ Filelist = ftp_nlist ($ conn, ".");

// Download an object
Ftp_get ($ conn, “data.zip ", “data.zip", FTP_BINARY );

// Close the connection
Ftp_quit ($ conn );

// An FTP connection is initially closed. PHP provides the ftp_connect () function, which uses the host name and port as the parameter. In the preceding example, the host name is "ftp.server.com". If the port is not specified, PHP uses "21" as the default port to establish a connection.

// After the connection is successful, ftp_connect () returns a handle. This handle will be used by subsequent FTP functions.
$ Conn = ftp_connect (ftp.server.com );

// Once a connection is established, use ftp_login () to send a user name and password. As you can see, this function ftp_login () uses handle from the ftp_connect () function to confirm that the user name and password can be submitted to the correct server.
Ftp_login ($ conn, "john", "doe ");

// Close connection
Ftp_quit ($ conn );

// Log on to the FTP server. PHP provides some functions that can obtain information about the system, files, and directories.
Ftp_pwd ()

// Obtain the current directory
$ Here = ftp_pwd ($ conn );

// Obtain the server-side system information ftp_0000ype ()
$ Server_ OS = ftp_cmdype ($ conn );

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

// Use the ftp_chdir () function in the directory. It accepts a directory name as the parameter.
Ftp_chdir ($ conn, "public_html ");

// Return to the parent directory of the Directory and use ftp_cdup ().
Ftp_cdup ($ conn );

// Create or move a directory. Use the ftp_mkdir () and ftp_rmdir () functions. Note: If ftp_mkdir () is created successfully, the new directory name is returned.
Ftp_mkdir ($ conn, "test ");

Ftp_rmdir ($ conn, "test ");

// Upload a file. The ftp_put () function is competent. You need to specify a local file name, the uploaded file name, and the transfer type. For example, if you want to upload the “abc.txt file, upload the file named "“xyz.txt", 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 (). It also requires a Server File name, the downloaded file name, and the transmission type as parameters. For example, if the server file is his.zip, download it to your host and name it hers.zip, the command is as follows:
Ftp_get ($ conn, “hers.zip ", “his.zip", FTP_BINARY );

// PHP provides two methods: a simple list of file names and directories, and a detailed list of file size, permissions, creation time, and other information.

// The first method uses the ftp_nlist () function, and the second method uses ftp_rawlist (). both functions require a directory name as the parameter. Both return the directory column as an array, and each element of the array is equivalent to a row in the list.
$ Filelist = ftp_nlist ($ conn, ".");

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

?>

FTPCopy codeThe Code is as follows: <? Php
/**
* Copy the FTP class of CodeIgniter
* Basic FTP operations:
* 1) login; connect
* 2) Current directory file list; filelist
* 3) Directory change; chgdir
* 4) rename/move; rename
* 5) create a folder; mkdir
* 6) Delete; delete_dir/delete_file
* 7) upload and 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 configure the 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 ID (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 ID (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 identification (ftp)
* @ Param string: 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 identification (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/move
*
* @ Access public
* @ Param string remote directory identification (ftp)
* @ Param string new directory ID
* @ Param boolean 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 an object
*
* @ Access public
* @ Param string File ID (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 A folder
*
* @ Access public
* @ Param string directory ID (ftp)
* @ Return boolean
*/
Public function delete_dir ($ path ){
If (! $ This-> _ isconn ()){
Return FALSE;
}

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

// Obtain the directory file list
$ Filelist = $ this-> filelist ($ path );

If ($ filelist! = False and count ($ filelist)> 0 ){
Foreach ($ filelist as $ item ){
// If the folder cannot be deleted, it may be a folder.
// Recursively call delete_dir ()
If (! @ Delete_file ($ item )){
$ This-> delete_dir ($ item );
}
}
}

// Delete a 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 ID (ftp)
* @ Return boolean
*/
Public function chmod ($ path, $ perm ){
If (! $ This-> _ isconn ()){
Return FALSE;
}

// Only PHP5 defines the function for modifying permissions (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 the directory file list
*
* @ Access public
* @ Param string directory ID (ftp)
* @ Return array
*/
Public function filelist ($ path = '.'){
If (! $ This-> _ isconn ()){
Return FALSE;
}

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

/**
* Disable 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 configure the 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 login
*
* @ Access private
* @ Return boolean
*/
Private function _ login (){
Return @ ftp_login ($ this-> conn_id, $ this-> username, $ this-> password );
}

/**
* Determine the 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 extension extensions from file names
*
* @ Access private
* @ Param string directory ID
* @ Return string
*/
Private function _ getext ($ filename ){
If (FALSE === strpos ($ filename ,'.')){
Return 'txt ';
}

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

/**
* Extended definition of FTP transmission mode ascii or binary from the suffix
*
* @ Access private
* @ Param string suffix Extension
* @ Return string
*/
Private function _ settype ($ ext ){
$ Text_type = array (
'Txt ',
'Text ',
'Php ',
'Phps ',
'Php4 ',
'Js ',
'Css ',
'Htm ',
'Html ',
'Phpml ',
'Shtml ',
'Log ',
'Xml'
);

Return (in_array ($ ext, $ text_type ))? 'Ascii ': 'binary ';
}

/**
* Error log records
*
* @ 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 */

DEMOCopy codeThe Code is 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.