16

我有一个 URL,用于保存我工作中的一些项目,它们主要是 MDB 文件,但也有一些 JPG 和 PDF。

我需要做的是列出该目录中的每个文件(已经完成)并为用户提供下载它的选项。

使用 PHP 是如何实现的?

4

4 回答 4

41

要读取目录内容,您可以使用readdir()并在我的示例中使用脚本download.php来下载文件

if ($handle = opendir('/path/to/your/dir/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
        }
    }
    closedir($handle);
}

download.php您可以强制浏览器发送下载数据,并使用basename ()确保客户端不会传递其他文件名,例如../config.php

$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;

if(!file_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);
}
于 2012-08-23T14:42:08.693 回答
3

这是不会下载coupt文件的代码

$filename = "myfile.jpg";
$file = "/uploads/images/".$filename;

header('Content-type: application/octet-stream');
header("Content-Type: ".mime_content_type($file));
header("Content-Disposition: attachment; filename=".$filename);
while (ob_get_level()) {
    ob_end_clean();
}
readfile($file);

我已经包含了 mime_content_type ,它将返回文件的内容类型。

为了防止文件下载损坏,我添加了 ob_get_level() 和 ob_end_clean();

于 2019-12-05T07:41:45.077 回答
2

如果可以从浏览器访问该文件夹(不在 Web 服务器的文档根目录之外),那么您只需输出指向这些文件位置的链接。如果它们在文档根目录之外,您将需要有链接、按钮等指向 PHP 脚本,该脚本处理从它们的位置获取文件并流式传输到响应。

于 2012-08-23T14:41:25.440 回答
2

这是一个更简单的解决方案,可以列出目录中的所有文件并下载它。

在你的 index.php 文件中

<?php
$dir = "./";

$allFiles = scandir($dir);
$files = array_diff($allFiles, array('.', '..')); // To remove . and .. 

foreach($files as $file){
     echo "<a href='download.php?file=".$file."'>".$file."</a><br>";
}

scandir() 函数列出指定路径内的所有文件和目录。它适用于 PHP 5 和 PHP 7。

现在在download.php

<?php
$filename = basename($_GET['file']);
// Specify file path.
$path = ''; // '/uplods/'
$download_file =  $path.$filename;

if(!empty($filename)){
    // Check file is exists on given path.
    if(file_exists($download_file))
    {
      header('Content-Disposition: attachment; filename=' . $filename);  
      readfile($download_file); 
      exit;
    }
    else
    {
      echo 'File does not exists on given path';
    }
 }
于 2017-05-22T05:48:19.403 回答