PHP list directory and delete or download files

醉酒当歌 提交于 2019-12-23 05:08:26

问题


I have a directory on my server, I want to list all the files in it with checkboxes and either delete or download them after choosing.

So far I can list and delete fine using this form, ticking checkboxes and pressing the button. But I also sometimes need to download files to my local machine. Either by ticking the checkbox or right-clicking the file name and downloading with 'save file as' in Chrome browser. But I can't get it working.

How can I download these files?

My page is called download-ui.php

<?php

if(isset($_POST['Submit']))
    {
    }      
      foreach ($_POST['select'] as $file) {

    if(file_exists($file)) {
        unlink($file); 
    }
    elseif(is_dir($file)) {
        rmdir($file);
    }
}

$files = array();
$dir = opendir('.');
    while(false != ($file = readdir($dir))) {
        if(($file != ".") and ($file != "..") and ($file != "download-ui.php") and ($file != "error_log")) {
                $files[] = $file; 
        }   
    }

    natcasesort($files);
?>

<form id="delete" action="" method="POST">

<?php
echo '<table><tr>'; 
for($i=0; $i<count($files); $i++) { 
    if ($i%5 == 0) { 
        echo '</tr>';
        echo '<tr>'; 
    }       
    echo '<td style="width:180px">
            <div class="select-all-col"><input name="select[]" type="checkbox" class="select" value="'.$files[$i].'"/>
            <a href="download-ui.php?name='.$foldername."/".$files[$i].'" style="cursor: pointer;">'.$files[$i].'</a></div>
            <br />
        </td>';
}
echo '</table>';
?>
</table>
<br>
<button type="submit" form="delete" value="Submit">Delete File/s</button>
</form><br>

回答1:


The download-ui.php have to be something like:

//Only enter if there is some file to download.
if(isset($_GET['name']){
  $file = basename($_GET['name']); //change if the url is absolute

  if(!$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-Transfer-Encoding: binary");

    // read the file from disk
    readfile($file);
  }
}

//your form

This way you are forcing to download the file. If you want it better, you can make a AJAX call when click on 'download' pointing to that url, and the file will be downloaded async, like:

$.ajax({
    url: 'download-ui.php',
    type: 'POST',
    success: function() {
        window.location = 'download-ui.php';
    }
});

But without AJAX will work too.

Check this: Download files from server php

Hope it helps!



来源:https://stackoverflow.com/questions/44110643/php-list-directory-and-delete-or-download-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!