Skip to content

Connecting to SFTP with PHP

3 min read

If you need to connect to SFTP using PHP then the simplest approach I’ve found is to use phpseclib, a library of functions for secure communications.

The library is a Composer package so you will need to have 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 versions of SFTP.

To initiate a connection a new object of SFTP is created with the address of the 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('');

if (!$sftp->login('username', 'password')) {
	throw new Exception('Login failed');

If we’ve got a private key we need to use the RSA class so that we can pass the key in place of the password to the SFTP::login() method:-

use phpseclib\Crypt\RSA;
use phpseclib\Net\SFTP;

$sftp = new SFTP('');

$Key = new RSA();
// If the private key has a passphrase we set that first
// Next load the private key using file_gets_contents to retrieve the key

if (!$sftp->login('username', $Key)) {
	throw new Exception('Login failed');

The SFTP class provides methods for SFTP similar to those provided by PHP’s FTP extension. 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():-


To get a file from the remote server use get():-

$sftp->get('remote_file', 'local_file');

This saves the remote_file to local_file. If the second parameter is left empty 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 are many other methods available and can be 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 that phpseclib provides a simple way of working with a SFTP connection.

© 2024 Andy Carter