-1

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.

Whos Joe
  • 1
  • 1
  • 1
    Sounds fine. What have you tried so far? Where are you stuck? – Nico Haase Apr 15 '20 at 13:02
  • i can get a list of files, but im unsure of how to download them – Whos Joe Apr 15 '20 at 22:35
  • that is as far as ive gotten – Whos Joe Apr 15 '20 at 22:43
  • I feel like the way to do it is to have an input that will execute ```readfile($filename);```, but once again, i am unsure of how to do it – Whos Joe Apr 15 '20 at 22:53
  • Does https://stackoverflow.com/questions/1465573/forcing-to-download-a-file-using-php help? That's one of the many solutions I've found using my favorite search engine. If that does not help, please edit your question to contain your attempts, and a clarification about **why** other tutorials did not help – Nico Haase Apr 16 '20 at 05:35
  • That does help of where a good place to start is, but is not what i am trying to do. i have edited the question to hopefully make it more clear – Whos Joe Apr 16 '20 at 06:02
  • No, I don't get the difference: the file is not downloaded, but what happens instead? And what have you tried to resolve that? – Nico Haase Apr 16 '20 at 06:51
  • It just opens the file on the browser, as if the files were just clickable links. – Whos Joe Apr 17 '20 at 21:05

1 Answers1

0

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);
  }
?>
Whos Joe
  • 1
  • 1