PushApp CO
PushApp CO

Reputation: 11

File downloaded from SFTP server using PHP fopen with ssh2.sftp:// URI is empty

I'm trying to download a file from the server using SFTP connection and save it on my server but the file is empty.

$connection = ssh2_connect('{my server ip}', 22);
ssh2_auth_password($connection, '{user}', '{password}');
$sftp = ssh2_sftp($connection);
$file = "test.txt";
$target_path = "ssh2.sftp://$sftp/public_html/$file";
$stream = fopen($target_path, 'r');
fopen($file, "w");
fclose($stream);

Upvotes: 0

Views: 262

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202088

You never copy the data between the opened files/handles. Easy way to do that is using stream_copy_to_stream:

$local_stream = fopen($file, "w");
stream_copy_to_stream($stream, $local_stream);
fclose($local_stream);

As @KenLee commented, if your server supports SCP too (most servers that support SFTP support SCP), you can replace 6 lines of the code with simple ssh2_scp_recv:

ssh2_scp_recv($connection, "/public_html/$file", $file);

Upvotes: 1

Related Questions