[英]How do I download a spisific file in a directory with PHP?
在我正在制作的 web 服务器中,我正在制作文件共享。 这是一些 PHP 代码,列出了名为“test”的目录中的所有文件。
<?php
//Get a list of file paths using the glob function.
$fileList = glob('test/*');
//Loop through the array that glob returned.
foreach($fileList as $filename){
//Simply print them out onto the screen.
echo $filename, '<br>';
}
我想做的是在文件名旁边有一个按钮来下载文件。 有没有人有办法解决吗? 这是我尝试过的;
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$thelist .= '<li><a href="'.$file.'">'.$file.'</a></li>';
}
}
closedir($handle);
}
?>
<h1>List of files:</h1>
<ul><?php echo $thelist; ?></ul>
这将显示当前目录中所有文件的列表。 单击显示的文件后,它将仅显示文件内容。 但我试图而不是显示文件的内容,而是试图在单击所述文件时下载文件。
经过大量的试验和错误。 我找到了解决方案。 所需要做的就是在 href html 变量的末尾添加一个download
属性。 工作代码:
<?php
if ($handle = opendir('uploads/')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$thelist .= '<li><a href="uploads/'.$file.'" download>'.$file.'</a></li>';
}
}
closedir($handle);
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.