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

标签 php download sftp phpseclib

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

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

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

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

欢迎任何回复!

最佳答案

如果您将文件的直接链接添加到您的 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');
?>

不幸的是,如果文件大于您的服务器/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 Manual Documentation .使用 curl_exec() 而不将 CURLOPT_RETURNTRANSFER 选项设置为 true 会导致 curl 将输出(文件)直接发送到浏览器。

关于php - 如何使用 PHP 从 SFTP 服务器下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16145779/

相关文章:

python - 如何在不解码的情况下在 Python 中下载带有请求的 .gz 文件?

java - 实际下载链接

html - 如何使用 HTML 5 从服务器访问和下载文件

查询中的 Php postgresql 变量

php - Laravel 5.x 如何使用路由名称获取 Controller 名称?

php - 文本文件到一个数组?

python - Paramiko 上传文件成功但为空

php - 如何在android应用程序和php服务器之间同步数据?

python - 如何做 sftp python 3?

python - 如何使用 Paramiko 从 SFTP 服务器下载最新文件而不使用循环?