我有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>";
}
答案 0 :(得分:1)
您在生成的<a>
标记中的链接指向不包含链接文件的Web服务器。
您需要做的是链接到PHP脚本,并为其指定要下载的文件的名称。然后,该脚本将从FTP服务器下载文件,并将下载的文件传递回用户(到Web浏览器)。
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 wrappers。如果您的Web服务器上不允许这样做,则必须更努力地使用FTP功能。看到
PHP: How do I read a file from FTP server into a variable?
尽管对于一个真正正确的解决方案,您应该提供一些与文件相关的HTTP标头,例如Content-Length
,Content-Type
和Content-Disposition
。
上述琐碎的示例还将首先将整个文件从FTP服务器下载到Web服务器。只有这样,它才会开始将其流式传输给用户(Web浏览器)。这既浪费时间,又浪费网络服务器上的内存。
有关更好的解决方案,请参见Download file via PHP script from FTP server to browser with Content-Length header without storing the file on the web server。
您可能还想自动检测Content-Type
,除非您的所有文件都属于同一类型。