如何使用 PHP 从 SFTP 服务器下载文件

cof*_*uts 3 php sftp download phpseclib

我希望允许用户直接从 sftp 服务器下载文件,但在浏览器中。

我找到了读取文件并回显字符串的方法(使用 ssh2.sftp 或 phpseclib 连接),但我需要下载,而不是读取。

另外,我看到的解决方案建议从 sftp 服务器下载到 Web 服务器,然后使用 readfile() 从 Web 服务器到用户的本地磁盘。但这意味着两次文件传输,如果文件很大,我想这会很慢。

可以直接从sftp下载到用户磁盘吗?

为任何回应干杯!

Rei*_*son 5

如果您将文件的直接链接添加到 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将输出(文件)直接发送到浏览器。