PHP: SFTP with phpseclib and ssh key

First you’ll need download / install phpseclib.

Here’s how to connect to the server with ssh key with this library:

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

$sftp = new SFTP($host); // connect to host

// get the key
$key = new RSA();

// connect to server
$sftp->login($user, $key);

// now do your sftp operations


  • Line 8: this will return false if key isn’t loaded, eg the ssh key file doesn’t exist.
  • Line 11: this will return false login fails.

You can find examples of how to use the lib here.

Leave a Reply

Your email address will not be published. Required fields are marked *