How to implement SFTP in PHP

Source: Internet
Author: User
Tags ftp connection ftp client file transfer protocol ftp protocol
This article mainly introduces the use of the SFTP Tutorial in PHP, this article explains the FTP protocol introduction, SSH protocol, SFTP protocol and other knowledge, and gives the FTP and SFTP operation class implementation code. We hope to help you.

<?php/** php using the SFTP tutorial Telnet, FTP, SSH, SFTP, SSL (a) FTP protocol introduction FTP (file Transfer Protocol, document Transfer Protocol) is a common protocol on the Internet One, people use FTP to realize the file transfer on the interconnection network. Like many other communication protocols, the FTP protocol also uses the client/server (Client/server) architecture. The user can connect FTP server via FTP protocol through various FTP client programs to upload or download files FTP command transmission and data transfer is a specific application of TCP/IP through different ports, it works on the seventh layer of the OSI model, On the fourth tier of the TCP model, the application layer, which uses TCP to transmit instead of UDP, so that the FTP client will pass a well-known "three handshake" process before establishing a connection with the server, the significance of which is that the connection between the client and the server is reliable and is oriented to the connection,    Provides a reliable guarantee for the transmission of data. (b) SSH protocol ssh is all called Secureshell, can report all the transmission data awakened encryption, so that the ' middleman ' will not be able to obtain the data we transmit at the same time, the transmission of data is compressed, can speed up the transmission. SSH has many functions that can replace Telnet Also available for Ftppop, the most important part of the framework for providing a secure channel SSH protocol is three protocols: * The Transport Layer Protocol (the Transport layer Protocol) provides server authentication, data confidentiality, information integrity and other support; * User authentication Protocol (the  User authentication Protocol) provides client identification for the server, and the connection protocol (the Connection Protocol) multiplexing The encrypted information tunnel into a number of logical channels for use in higher-level application protocols;     Various high-level application protocols can be relatively independent of the SSH basic system, and rely on this basic framework, through the connection protocol using SSH security mechanism. (c) The protocol for FTP transmission using the SSH protocol called SFTP (secure file transfer) SFTP and FTP are file transfer protocols. Difference: SFTP is an SSH protocol (SSH is an encrypted Telnet protocol), as long as the sshd server is started, it is available, and SFTP security is high, it does not require the FTP server to boot. SFTP = SSH + FTP (secure file Transfer Protocol). Because FTP is transmitted in plaintext, there is noSecurity, while SFTP is SSH-based, the transmitted content is encrypted and more secure. At present the network is not very safe, used telnet to use SSH2 (SSH1 has been cracked). SFTP This tool is the same as FTP usage. However, its transfer files are encrypted by SSL, even if intercepted and can not be cracked.      and SFTP compared to FTP features more, some of the settings of the file attributes *///Note here just to introduce FTP, and did not do validation;    Class ftp{//Initial configuration is NULL private $config =null;         The connection is null private $conn = NULL;        Public function init ($config) {$this->config = $config; }//FTP connection Public function connect () {return $this->conn = ftp_connect ($this->config[' host '), $th     is->config[' Port ')); }//Transport data Transfer layer protocol, get data true or false public function download ($remote, $local, $mode = ' auto ') {return $r  Esult = @ftp_get ($this->conn, $localpath, $remotepath, $mode); }//Transmit Data Transfer layer protocol, upload true or false public function upload ($remote, $local, $mode = ' auto ') {return $result = @ft  P_put ($this->conn, $localpath, $remotepath, $mode);    }//Delete file Public function remove ($remote) {return $result = @ftp_delete ($this->conn_id, $file);      }     }    Using $config = Array (' hostname ' = ' localhost ', ' username ' = ' root ', ' password ' = ' R ')  Oot ', ' port ' = 21); $FTP = new FTP (), $ftp->connect ($config), $ftp->upload (' Ftp_err.log ', ' ftp_upload.log '); $ftp->download (' FTP   _upload.log ', ' ftp_download.log ');    /* Write SSH-based FTP class based on the above three protocols we know that there are two ways to authenticate: public key; password;(1) login with password (2) password-free login is to use public key login */class sftp{//initial configuration is null    Private $config =null;          The connection is null private $conn = NULL;         Whether to use secret key to log on private $use _pubkey_file= false;     Initialize Public function init ($config) {$this->config = $config;  }//Connect SSH, there are two ways to connect (1) Use password//(2) Use secret key public function connect () {$methods [' hostkey '] = $use _pubkey_file?         ' Ssh-rsa ': [];        $con = Ssh2_connect ($this->config[' host '), $this->config[' Port '], $methods);  (1) When using the secret key, if ($use _pubkey_file) {//user authentication protocol $RC = Ssh2_auth_pubkey_file (              $conn, $this->config[' user '], $this->config[' Pubkey_file '),        $this->config[' Privkey_file '], $this->config[' passphrase ')); (2) Use login user name and login password}else{$RC = Ssh2_auth_password ($conn, $this->conf_[' user '], $this->conf_[' pas               SWD ']);     } return $RC; }//Transmit Data Transfer layer protocol, get the public function download ($remote, $local) {return ssh2_scp_recv      ($this->conn_, $remote, $local); }//Transmit Data Transfer layer protocol, write FTP server data public function upload ($remote, $local, $file _mode=0664) {return SSH2_SCP                _send ($this->conn_, $local, $remote, $file _mode);            }//Delete file Public function remove ($remote) {$sftp = Ssh2_sftp ($this->conn_);     $RC = false;                         if (Is_dir ("ssh2.sftp://{$sftp}/{$remote}")) {$RC = false; SSH DeleteFolder $RC = Ssh2_sftp_rmdir ($sftp, $remote);            } else {//delete file $RC = Ssh2_sftp_unlink ($sftp, $remote);                     } return $RC; }} $config = ["Host" = "192.168.1.1",//FTP address "user" = "* *", "port" = "" "," Pu Bkey_path "=" and "/root/.ssh/id_rsa.pub",//The storage address of the public key "Privkey_path" = "/root/.ssh/id_rsa",//The storage address of the private key); $handle = new Sftpaccess (); $handle->init ($config); $RC = $handle->connect (); $handle->getdata (remote, $local) ;

Related recommendations:

PHP File Reading Series method

Use PHP ssh2 extension to implement SVN auto-submit to test suit, ssh2svn_php tutorial

PHP SSH2 extended Operation class

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.