This is code that we use for the ssh2 library (with password auth). You will need to replace the auth function for key usage: https://www.php.net/manual/en/function.ssh2-auth-pubkey-file.php
$error = false;
$connection = ssh2_connect('host.name', 22);
if ($connection) {
if (ssh2_auth_password($connection, 'username', 'password')) {
$sftp = ssh2_sftp($connection);
if ($sftp) {
try {
$sftpStream = fopen('ssh2.sftp://' . intval($sftp) . MODULE_SFTP_FOLDER . $filename_remote, 'w');
if (!$sftpStream) {
throw new Exception("Could not open remote file: $filename_remote");
}
$data_to_send = file_get_contents('manifests/' . $filename);
if ($data_to_send === false) {
throw new Exception("Could not open local file: manifests/$filename.");
}
if (fwrite($sftpStream, $data_to_send) === false) {
throw new Exception("Could not send data from file: manifests/$filename.");
}
fclose($sftpStream);
$success = true;
} catch (Exception $e) {
$success = false;
$error = $e->getMessage();
error_log('Exception: ' . $e->getMessage());
if ($sftpStream) fclose($sftpStream);
}
if (!$success) {
$error = true;
}
ssh2_exec($connection, 'exit');
unset($connection);
} else {
$error = true;
}
} else {
$error = true;
}
} else {
$error = true;
}
$connection = ssh2_connect('host.name', 22);
if ($connection) {
if (ssh2_auth_password($connection, 'username', 'password')) {
$sftp = ssh2_sftp($connection);
if ($sftp) {
try {
$sftpStream = fopen('ssh2.sftp://' . intval($sftp) . MODULE_SFTP_FOLDER . $filename_remote, 'w');
if (!$sftpStream) {
throw new Exception("Could not open remote file: $filename_remote");
}
$data_to_send = file_get_contents('manifests/' . $filename);
if ($data_to_send === false) {
throw new Exception("Could not open local file: manifests/$filename.");
}
if (fwrite($sftpStream, $data_to_send) === false) {
throw new Exception("Could not send data from file: manifests/$filename.");
}
fclose($sftpStream);
$success = true;
} catch (Exception $e) {
$success = false;
$error = $e->getMessage();
error_log('Exception: ' . $e->getMessage());
if ($sftpStream) fclose($sftpStream);
}
if (!$success) {
$error = true;
}
ssh2_exec($connection, 'exit');
unset($connection);
} else {
$error = true;
}
} else {
$error = true;
}
} else {
$error = true;
}
Hope that helps,
Kind regards,
Scott
Scott
First Class Watches
9 Warwick Road
Kenilworth
CV8 1HD
Warwickshire
Kenilworth
CV8 1HD
Warwickshire
United Kingdom
On Mon, 25 Jan 2021 at 13:19, Jonesy via php-general <php-general@xxxxxxxxxxxxx> wrote:
On Mon, 25 Jan 2021 07:51:56 -0500, David Spector wrote:
> I have a question about uploading a file (text.txt) securely in PHP
> using the SFTP protocol and a public/private key pair.
rsync: an alternate to sftp:
# Upload to example.com/dir/
rsync -avzhe ssh \
/local_dir/dir/TheFile.ext \
remote_user@xxxxxxxxxxx:/public_html/dir/
HTH
Jonesy
--
Marvin L Jones | Marvin | W3DHJ.net | linux
38.238N 104.547W | @ jonz.net | Jonesy | FreeBSD
* Killfiling google & XXXXbanter.com: jonz.net/ng.htm