I wish to use code in PHP to authenticate using keypair over SFTP. I am using Laravel, however I wish to code using seperate SFTP.
From research I have:
composer require phpseclib/phpseclib:~3.0
Which shows in vendor directory.
In the class I wish to use it I have:
use phpseclib3\Crypt\RSA;
use phpseclib3\Net\SFTP;
and in the current test development method definition:
public static function sftp_listDirectoryItems($connection, $dir, $optargs = []) {
$sftp = new SFTP($connection);
$privateKey = new RSA();
$noop = 1;
}
Which gives this
I am trying to follow the guide by
Connect to SFTP using PHP and private key
However as above, its not working for basic testing.
Hopefull someone can put me in the right direction as according to Barmar the example I found is out of date.
I currently have Filezilla using an SSH keypair, and I would like to use PHP to point to the same key file for authentication and programatically manipulate the files in the same way.
I would hope I could then gain the same functionality as the OLD example code shows:
// load the private key
$privateKey->loadKey(file_get_contents('/path/to/privatekey.pem'));
// login via sftp
if (!$sftp->login('username', $privateKey)) {
throw new Exception('sFTP login failed');
}
// now you can list what's in here
$filesAndFolders = $sftp->nlist();
// you can change directory
$sftp->chdir('coolstuffdir');
// get a file
$sftp->get('remoteFile', 'localFile');
// create a remote new file with defined content
$sftp->put('newfile.txt', 'new file content');
// put a local file
$sftp->put('remote.txt', 'local.txt', NET_SFTP_LOCAL_FILE);
The code you are trying is for old version of phpseclib.
In the latest version, use:
$key = PublicKeyLoader::load(file_get_contents('/path/to/privatekey.pem'));