Recently I had to use ssh2 through php in order to send files from one server to another. I don’t know why, I was getting a error that was not actually very common on the Internet. My code was:

$connection = ssh2_connect($host, $port);
ssh2_scp_send($connection, $path_origin, $path_target, 0644);

The connection was correctly placed, but when trying to copy the file, I got:

Warning: ssh2_scp_send(): Failure creating remote file: Invalid ACK response from remote

After looking for the solution, I finally found something [not really related to this issue]. There are other ways of copying files through ssh using php, and that’s what I did. Here is the workaround I found:

<?php
$srcFile = '/path_to_origin_file';
$dstFile = '/path_to_server_file';

$host = 'ssh_host';
$port = '22';
$username = 'ssh_user';
$password = 'ssh_password';

// Create connection the the remote host
$conn = ssh2_connect($host, $port);
ssh2_auth_password($conn, $username, $password);

// Create SFTP session
$sftp = ssh2_sftp($conn);

$sftpStream = fopen('ssh2.sftp://'.$sftp.$dstFile, 'w');

try {

    if (!$sftpStream) {
        throw new Exception("Could not open remote file: $dstFile");
    }

    $data_to_send = file_get_contents($srcFile);

    if ($data_to_send === false) {
        throw new Exception("Could not open local file: $srcFile.");
    }

    if (fwrite($sftpStream, $data_to_send) === false) {
        throw new Exception("Could not send data from file: $srcFile.");
    }

    fclose($sftpStream);

} catch (Exception $e) {
    error_log('Exception: ' . $e->getMessage());
    fclose($sftpStream);
}
?>
Categories: Development

1 Comment

Paul W. · March 6, 2014 at 9:58 pm

After messing with ssh2_scp_send() for two days, I determined that the filename must be quoted and permissions string unquoted. In your case, I would try the following:

ssh2_scp_send($connection, “$path_origin”, “$path_target”, 0644);

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.