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(); $key->loadKey(file_get_contents($keyfile)); // connect to server $sftp->login($user, $key); // now do your sftp operations
Notes:
- 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.