如果您将文件的直接链接添加到 html(即下载文本),则不需要任何 php 即可允许用户直接从 SFTP 服务器下载。当然,如果您不想公开 ftp 服务器的凭据,这将不起作用。
如果您希望通过服务器从 SFTP 提取文件,根据定义,您必须先将文件下载到服务器,然后再将其发送回用户浏览器。
为此,有很多很多的解决方案。最少的开销可能来自使用 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');
?>
Run Code Online (Sandbox Code Playgroud)
不幸的是,如果文件大于服务器/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);
Run Code Online (Sandbox Code Playgroud)
有关使用 cURL 的更多信息可以在PHP 手册文档中找到。使用curl_exec()而不将CURLOPT_RETURNTRANSFER选项设置为true会导致curl将输出(文件)直接发送到浏览器。