简体   繁体   中英

Delete a file from a directory

First off, I know to use Unlink to delete a singular file from a directory. However, what I want to know is how to set that up so I can have an html interface and be able to choose through all the files in a directory.

Code would be nice, but it is unfair to ask that of you fine people. So a shove in the right direction would be just as good.

This code lists out all the files in the given directory with delete link. When delete button is clicked, it calls a php file to delete the file using ajax(jquery) function. Check whether more than one file don't have the same name.

list all files in a directory

<?php
$directory  = "your directory path"; 
$images = scandir($directory);
$ignore = Array(".", "..");
$count=1;
echo '<table border=1>';
foreach($images as $dispimage){
    if(!in_array($dispimage, $ignore)){
    echo "<tr id='del$count'><td>$count</td><td>$dispimage</td><td><input type='button' id='delete$count' value='Delete' onclick='deleteFile(\"$dispimage\",$count,\"$directory\");'></td></tr>";
    $count++;
    }
}
echo '</table>';
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function deleteFile(fname,rowid,directory)
{
    $.ajax({ url: "deletefile.php",
        data: {"filename":fname,"directory":directory},
        type: 'post',
        success: function(output) {
          alert(output);
          $("#del"+rowid).remove();
        }
    });
}
</script>

deletefile.php

<?php
$filename = $_POST['filename'];
$path = $_POST['directory'];
if(file_exists($path."/".$filename)) { 
 unlink($path."/".$filename); //delete file
}
?>

You can refer here for an open source version of php file manager. You can review its code or directly use it. It is not easy to do that operation by pasting sample code here.

The following function is for deleting whole directory.

function readDirectory($dir){
$dir = opendir($dir);
while (($file = readdir($dir)) !== false)
  {
    if($file!="." and $file!=".."){
        echo "filename: " . $file . "<br />";
    }
  }
closedir($dir);
}
function rrmdir($dir) {
    if (is_dir($dir)) {
    $objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir")rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}   
reset($objects);
rmdir($dir);
}
}

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