问题
I'm looking to allow a user to download a file directly from an sftp server, but in the browser.
I've found methods to read the file and echo the string (connections using ssh2.sftp or phpseclib) but I need to download, rather than read.
Also, I've seen solutions that suggest downloading from the sftp server to the web server, then use readfile() from the web server to the user's local disk. But this means two file transfers, and if the file is large I imagine this would be slow.
Can you download directly from sftp to the user's disk?
Cheers for any responses!
回答1:
You don't need any php in order to allow the user to download directly from the SFTP server, if you add a direct link to the file to your html (i.e. Download Text). Of course this won't work if you don't want to make the credentials for the ftp server public.
If you are looking to pull the file from the SFTP through your server, you, by deffinition, must download the file to the server before sending it back out to the users browser.
For this there are many, many solutions. The least overhead would probably come from using phpseclib as below
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
//adds the proper headers to tell browser to download rather than display
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"filename.remote\"");
// outputs the contents of filename.remote to the screen
echo $sftp->get('filename.remote');
?>
Unfortunately, if the file is larger than is allowed in memory by your server/php configuration, then this well cause problems.
If you want to take it a step further, you might try
//adds the proper headers to tell browser to download rather than display
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"filename.remote\"");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "sftp://full_file_url.file"); #input
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
curl_setopt($curl, CURLOPT_USERPWD, "$_FTP[username]:$_FTP[password]");
curl_exec($curl);
curl_close($curl);
More information on using cURL can be found in the PHP Manual Documentation. Using curl_exec() without setting the CURLOPT_RETURNTRANSFER option to true causes curl to send the output (the file) directly to the browser.
来源:https://stackoverflow.com/questions/16145779/how-to-download-a-file-from-an-sftp-server-using-php