首页 > 解决方案 > 列出并从 FTP 下载点击的文件

问题描述

我有 FTP,我需要在上传目录中列出 FTP 中的所有文件,单击任何列出的文件后,它将从 FTP 下载特定文件。

它在上传目录中列出了我的文件,但是当我尝试下载文件时,它会键入“无文件”

我的代码:

    // connect and login to FTP server
$ftp_server = "IP";
$ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
$login = ftp_login($ftp_conn, "name", "password");

// list all files in upload directory and with "a" download file from FTP
$target_dir = "uploads/";
$files = ftp_nlist($ftp_conn, $target_dir);
foreach($files as $file) {
    echo "<a href='$file' download>$file</a>";
    echo "<br>";
}

标签: phpfiledownloadftp

解决方案


生成<a>标记中的链接指向不包含链接文件的 Web 服务器。

您需要做的是链接到一个 PHP 脚本,给它一个要下载的文件的名称。然后,该脚本将从 FTP 服务器下载文件并将下载的文件传回给用户(给网络浏览器)。

echo "<a href=\"download.php?file=".urlencode($file)."\">".htmlspecialchars($file)."</a>";

download.php脚本的一个非常简单的版本:

<?

header('Content-Type: application/octet-stream');

echo file_get_contents('ftp://username:password@ftp.example.com/path/' . $_GET["file"]);

download.php脚本使用FTP URL 包装器。如果您的网络服务器不允许这样做,您必须使用 FTP 功能更加困难。请参阅 PHP:如何将文件从 FTP 服务器读取到变量中?


尽管对于一个真正正确的解决方案,您应该提供一些与文件相关的 HTTP 标头,Content-Length例如Content-TypeContent-Disposition.

此外,上述简单示例将首先将整个文件从 FTP 服务器下载到网络服务器。只有这样它才会开始将其流式传输给用户(网络浏览器)。什么是浪费时间和网络服务器上的内存。

如需更好的解决方案,请参阅通过 PHP 脚本从 FTP 服务器下载文件到带有 Content-Length 标头的浏览器,而不将文件存储在 Web 服务器上

您可能还想自动检测Content-Type,除非您的所有文件都属于同一类型。


一个有关通过网页实现 FTP 上传的相关问题:
Displaying recent uploading images from remote FTP server in PHP


推荐阅读