[英]How to download a file from an SFTP server using PHP
我希望允许用户直接从sftp服务器下载文件,但是在浏览器中。
我找到了读取文件和回显字符串的方法(使用ssh2.sftp或phpseclib的连接),但我需要下载,而不是阅读。
此外,我已经看到了建议从sftp服务器下载到Web服务器的解决方案,然后使用从Web服务器到用户本地磁盘的readfile()。 但这意味着两个文件传输,如果文件很大,我想这会很慢。
你能直接从sftp下载到用户的磁盘吗?
欢呼任何回复!
如果您将文件的直接链接添加到您的html(即下载文本),则不需要任何php以允许用户直接从SFTP服务器下载。 当然,如果您不想公开ftp服务器的凭据,这将不起作用。
如果您希望通过服务器从SFTP中提取文件,则必须通过deffinition将文件下载到服务器,然后再将其发送回用户浏览器。
为此,有许多很多解决方案。 最小的开销可能来自使用如下的phpseclib
<?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');
?>
不幸的是,如果文件大于你的服务器/ php配置在内存中允许的文件,那么这很好会导致问题。
如果你想更进一步,你可以试试
//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);
有关使用cURL的更多信息,请参阅PHP手册文档 。 使用curl_exec()而不将CURLOPT_RETURNTRANSFER选项设置为true会导致curl将输出(文件)直接发送到浏览器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.