Bootstrap FreeKB - PHP - SCP (Secure Copy Protocol) using SFTP (Secure FTP)
PHP - SCP (Secure Copy Protocol) using SFTP (Secure FTP)

Updated:   |  PHP articles

ssh2_sftp can be used to transfer a file from a local system to a remote system. Before using ssh2_sftp, 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 "Successfully connect to SSH server $server <br />";
}
else {
  echo "Failed to connect to SSH server $server <br />";
  exit();
}

$username = "john.doe";
$password = "itsasecret";
$authenticate = ssh2_auth_password($connection, $username, $password);

if ($authenticate) {
  echo "Successfully authenticated to SSH server $server as $username <br />";
}
else {
  echo "Failed to authenticate to SSH server $server as $username <br />";
  exit();
}

$sftp = ssh2_sftp($connection);
if ($sftp) {
  echo "ssh2_sftp connection successful <br />";
}
else {
  echo "ssh2_sftp connection failed <br />";
  exit();
}

$local_file  = "/tmp/foo.txt";
$remote_file = "/tmp/foo.txt";

$sftpStream = @fopen("ssh2.sftp://$sftp/$remote_file", 'w');

if ($sftpStream) {
  echo "successfully created $remote_file on $server<br />";
}
else {
  echo "failed to create $remote_file on $server<br />";
  exit();
}

$local_file_content = @file_get_contents("$local_file");

if ($local_file_content === false) {
  echo "Failed to read the content of $local_file on PHP system<br />";
  exit();
}
else {
  echo "Successfully read the content of $local_file on the PHP system<br />";
}

if (@fwrite($sftpStream, $local_file_content) === false) {
  echo "Failed to send the content of $local_file on the PHP system to $remote_file on $server<br />";
  exit();
}
else {
  echo "Successfully sent the content of $local_file on the PHP system to $remote_file on $server<br />";
}

fclose($sftpStream);
ssh2_exec($connection, 'exit');

?>

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter ec7ebf in the box below so that we can be sure you are a human.