PHP - SCP (Secure Copy Protocol)

by
Jeremy Canfield |
Updated: February 16 2022
| PHP articles
The ssh2_scp_send function can be used to send a file to an SSH system using SCP (Secure Copy Protocol). Before using the ssh2_scp_send function, you will need to establish a connection to the SSH server using the ssh2_connection function and then the ssh2_auth_password or ssh2_auth_pubkey_file function to authenticate to the SSH server.
In this example, the /tmp/foo.txt file on the system running PHP will be uploaded to /tmp/foo.txt on the SSH server over SCP.
<?php
$server = "server1.example.com";
$connection = ssh2_connect($server, 22);
if (!$connection) {
echo "Failed to connect to SSH server $server <br />";
}
else {
echo "Successfully connect to SSH server $server <br />";
}
$username = "john.doe";
$password = "itsasecret";
$authenticate = ssh2_auth_password($connection, $username, $password);
if (!$authenticate) {
echo "Failed to authenticate to SSH server $server as $username <br />";
}
else {
echo "Successfully authenticated to SSH server $server as $username <br />";
}
$local_file = "/tmp/foo.txt";
$remote_file = "/tmp/foo.txt";
$send = ssh2_scp_send($connection, $local_file, $remote_file, 0644);
if (!$send) {
echo "Filed to $local_file to $remote_file on $server <br />";
}
else {
echo "Successfully send $local_file to $remote_file on $server <br />";
}
?>
Did you find this article helpful?
If so, consider buying me a coffee over at