简体   繁体   中英

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. here is some PHP code that lists all files in a directory called "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. 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);
  }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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