简体   繁体   English

如何在 PHP 的目录中下载 spisific 文件?

[英]How do I download a spisific file in a directory with PHP?

In the web sever that I'm making, I'm making a file share.在我正在制作的 web 服务器中,我正在制作文件共享。 here is some PHP code that lists all files in a directory called "test".这是一些 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>'; 
}

what im trying to do is have a button next to the file name that will download the file.我想做的是在文件名旁边有一个按钮来下载文件。 does anyone have a solution?有没有人有办法解决吗? This is something that i have tried;这是我尝试过的;

<?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>

this displays a list of all files in the current directory.这将显示当前目录中所有文件的列表。 Upon clicking on a displayed file, it will just display the file contents.单击显示的文件后,它将仅显示文件内容。 but im trying to instead of displaying the contents of the file, im trying to download the file upon clicking on said file.但我试图而不是显示文件的内容,而是试图在单击所述文件时下载文件。

after a lot of trial and error.经过大量的试验和错误。 I have found the solution.我找到了解决方案。 all that was needed to be done was to add a download attribute at the end of the href html variable.所需要做的就是在 href html 变量的末尾添加一个download属性。 working code:工作代码:

<?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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM