簡體   English   中英

如何使用PHP從SFTP服務器下載文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM