从服务器 php 下载文件
2022-08-31 00:08:16
我有一个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);
}
在你可以强制浏览器发送下载数据,并使用basename()来确保客户端不会传递其他文件名,如download.php
../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);
}
这是不会下载courpt文件的代码
$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();