PHP 用于通过网站从包含服务器上指定文件夹中文件的列表页面下载文件的脚本

PHP script for downloading files through website from a list page containing files in specified folder on server

我需要向其他非程序员展示他们可以从 FTP 服务器文件夹(我使用 WinSCP)下载的各种文件的选项

现在代码的问题是,如果你在PHP脚本中写了一个特定的文件名,你就可以毫无问题地下载它。但我需要的是让他们上传(效果很好),但也让他们能够(其他时间或其他人)从以前上传的文件中选择并下载他们选择的特定文件。

所以我们需要做的就是打开文件夹,显示其中的所有文件,然后能够从这些文件中选择一个并下载它。

有谁知道如何解决这个问题,甚至可能吗?

<?php
//uploads is the folder name at the ftp server
if ($handle = opendir('uploads/')) {
    while (false !== ($entry = readdir($handle)))
    {
        //
        if ($entry != "." && $entry != "..") {
            //download.php is the file where we write the code
            echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
        }
    }

    closedir($handle);//
}

// we are trying to get the files by listing it with .$file variable
$file = basename($_GET['file']);
$file = 'uploads/'.$file;

//here we are 
$mimi = $file;

if(!mimi_exists($file)){ // file does not exist
    die('file not found');
} else {
    header("Cache-Control: public"); //
    header("Content-Description: File Transfer");//
    header("Content-Disposition: attachment; filename=$file");//
    header("Content-Type: application/zip");//
    header("Content-Transfer-Encoding: binary");//

    // read the file from disk
    readfile($file);
}
?>

使用之前的代码,文件名(来自文件夹)被列出并显示为链接,但是当我们点击它们时没有任何动作。

代码

  1. 列出文件
  2. 下载文件

必须分开。


(虽然不是绝对必要),简单的方法是将它们放入单独的文件中,如 list.phpdownload.phplist.php 将生成一个下载链接列表,该列表将指向 download.php(您已经在 opendir ... closedir 块中执行的操作):

if ($handle = opendir('uploads/')) {
    while (false !== ($entry = readdir($handle)))
    {
        //
        if ($entry != "." && $entry != "..") {
            //download.php is the file where we write the code
            echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
        }
    }

    closedir($handle);//
}

download.php 将包含您的其余代码:

// we are trying to get the files by listing it with .$file variable
$file = basename($_GET['file']);
$filepath = 'uploads/'.$file;

if(!file_exists($filepath)){ // file does not exist
    die('file not found');
} else {
    header("Cache-Control: public"); //
    header("Content-Description: File Transfer");//
    header("Content-Disposition: attachment; filename=$file");//
    header("Content-Type: application/zip");//
    header("Content-Transfer-Encoding: binary");//

    // read the file from disk
    readfile($filepath);
}

(我已经用 file_exists 替换了你奇怪的 mimi_exists 并修复了内部 "upload" 文件路径被意外发送到浏览器的问题)


类似问题:.