我有一个URL,里面保存了我工作的一些项目,主要是MDB文件,但也有一些JPG和PDF文件。
我需要做的是列出该目录中的每个文件(已完成),并给用户提供下载选项。
如何使用PHP实现这一点?
我有一个URL,里面保存了我工作的一些项目,主要是MDB文件,但也有一些JPG和PDF文件。
我需要做的是列出该目录中的每个文件(已完成),并给用户提供下载选项。
如何使用PHP实现这一点?
您可以使用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);
}
这里是能避免下载损坏文件的代码
$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()函数。
这里有一个更简单的解决方案,可以列出目录中的所有文件并下载它。
在您的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';
}
}