PHP connected to FTP, found a very useful class library phpseclib. English original
Connecting to SFTP with PHP
If you need to connect to SFTP using PHP then the simplest approach I ' ve found are to use phpseclib, a library of F Unctions for secure communications.
The library is a Composer package so you'll need to has Composer installed, then just require the package as usual:-
$ composer require phpseclib/phpseclib
The library provides what it refers to as a "pure-PHP Implementation of SFTP" and supports the most widely used VE Rsions of SFTP.
To initiate a connection a new object of was created with the address of the SFTP
remote server passed to the constructor. To authenticate our SFTP connection we can pass the login credentials using SFTP::login()
:-
use phpseclib\Net\SFTP;
$sftp = new SFTP(‘www.example.com‘);
if ( ! $sftp ->login ' username ' ' password ' ) {throw new exception ( ' Login failed ' ) ;< Span class= "token punctuation" >}
If we ' ve got a private key we need to use the class so, we can pass the key in place of the password to the RSA
method:-
use phpseclib\Crypt\RSA;use phpseclib\Net\SFTP;
$sftp = new SFTP(‘www.example.com‘);
$Key=NewRsa();//If the private key has a passphrase we set that First $Key
-
>setpassword ( ' passphrase ' ) ; //Next load the private key using file_gets_contents to retrieve the Key $Key -> Loadkeyfile_get_contents ( ' Path_to_private_key '
if ( ! $sftp ->login ' username ' $Key ) {throw new exception ( ' Login failed ' ) ;< Span class= "token punctuation" >}
The SFTP
class provides methods for SFTP similar to those provided by PHP ' s ftpextension. For example, to get a list of files for the current directory we use nlist()
(equivalent of ftp_nlist
):-
$files = $sftp->nlist();
To change directory use chdir()
:-
$sftp->chdir(‘directory_name‘);
To get a file from the remote server use get()
:-
$sftp->get(‘remote_file‘, ‘local_file‘);
This saves remote_file
local_file
. If the second parameter is left empty and then the method returns the contents of the remote file if successful (otherwise it Returns false
).
To upload a file to the remote server use put()
:-
$sftp->put(‘remote_file‘, ‘contents for remote file‘);
There is many other methods available and can is found in the SFTP
class. The class is well documented with thorough comments. The above methods should get you started though.
Hopefully you can see this phpseclib provides a simple to working with aSFTP connection.
PHP Connection FTP