PHP unlink() Function

PHP unlink() Function

The PHP unlink() function can be used to delete files within specified directories. One such use of this function could be to remove images for a dynamic image gallery.

The code below can be used to delete multiple images in a specific folder. The post variables for $_POST['filenames'] is an array of each file which was selected for deleting. The foreach loop takes each file that you want to delete and uses the unlink($newdir) function to delete the file.

if ($_POST['mysubmit2']) {
foreach ($_POST["filenames"] as $filename) {
echo $filename;
// $newdir = getcwd()."/images/gallery/".$filename; // for live hosting
$newdir = getcwd()."\images\gallery\\".$filename;
unlink($newdir);
}
}




THE FORM

 //$dir =  getcwd()."/images/gallery" ; //for live host
        $dir =  getcwd()."\images\gallery" ; //for WAMP
        
        ?>

<form name="mydelete" method="post" action="<?php echo $_SERVER['PHP_SELF'] ; ?>" >        

<?php
//$dir    = $directory;
$files1 = scandir($dir);
foreach($files1 as $file){
if(strlen($file) >=3){
//$foil = strstr($file, 'jpg'); // As of PHP 5.3.0
$foil = $file;
//$pos = strpos($file, 'css');
if ($foil==true){
echo '<input type="checkbox" name="filenames[]" value="'.$foil.'" />';
// echo "<img width='130' height='38' src='images/gallery/$file' /><br/>"; // for live host
echo "<img width='130' height='38' src='/ABOOK/SORTING/gallery-dynamic/images/gallery/$file' /><br/>";
}
}
}?>
<input type="submit" name="mysubmit2" value="Delete">
</form>