I am currently using a similar version of the below code to transfer a file from a remote server to my web server and then redirecting to the web server copy of the file in a publicly accessible web location.
$tempfile = "/mylocalfolder/tempfile.wav"
if (file_exists($tempfile)) {
unlink($tempfile);
}
$selectedfile = htmlspecialchars($_GET["File"]);
$filelink = '/myremotefolder/'.$selectedfile;
$connection = ssh2_connect($remote_server_ip, 22);
ssh2_auth_password($connection, 'username', 'password');
//echo $filelink.','. $tempfile;
ssh2_scp_recv($connection, $filelink, "/mylocalfolder/tempfile.wav");
header( 'Location: /mylocalfolder/recording.wav' ) ;
I also get some files from amazon s3 using their api. When i use this method the api returns the file as an object so I am able to send it directly to the browser with the appropriate headers. like below example.
// Display the object in the browser
header("Content-Type: {$result['ContentType']}");
header("Content-Type: audio/wav");
echo $result['Body'];
}
My question is how can stream/get a file from a remote server and send it to the browser in the same way as the bottom version without creating a physical copy on the webserver. Many thanks in advance
You can use ssh2_sftp http://php.net/manual/en/function.ssh2-sftp.php ... you must install ssh2 bindings as PECL extension (http://php.net/manual/es/book.ssh2.php)
An example code may be ...
$sftp = ssh2_sftp($connection);
$remote = fopen("ssh2.sftp://$sftp/path/to/file", 'rb');
header( 'Content-type: ......');
while(!feof($remote)){
echo( fread($remote, 4096));
}
I have not tested the code, but it should work.
You can use phpseclib to download the file:
require_once 'Net/SFTP.php';
$connection = new Net_SFTP($remote_server_ip);
if (!$connection->login('username', 'password')) die('Login Error');
// set some appropriate content headers
echo $connection->get($filelink);
Or you can use the ssh2.sftp
wrapper - see SilvioQ's answer for that approach.
来源:https://stackoverflow.com/questions/35920490/how-can-i-fetch-a-remote-file-in-php-over-ssh-and-return-file-directly-to-the-br