How can I delete images in a folder that for example all have the name "john" in them. I am making a temporary image folder and I want to erase all of the users data on the temp folder after they're done. Thanks.
Make use of PHP's built in DirectoryIterator to iterate across all the files in the images/
directory you want to modify.
$name = 'John';
$dir = new DirectoryIterator('images'); //In this case the images directory
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
//Is a valid file name
$filename = $fileinfo->getFilename();
//Now you have access to the filename make appropriate modifications. Below is a quick naive demonstration.
if (strpos($filename, $name)) {
//We have fulfilled the 'John' condition, delete the file
unlink('images/' . $filename);
}
}
}
You may need to modify the variables and directory names accordingly based on absolute
or relative
pathing to your situation. Make sure you have the appropriate permissions to (if relevant).
Something like this:
<?php
$NameToDelete = $_GET['name']; //ex: file.php?name=john
$Folder = "/images/"; //The folder you want to delete from
$FileType = array( //All the filetypes (in this case some image types
'jpg',
'png',
'bmp',
'jpeg'
);
foreach($FileType as $Type){//For EACH filetype as type
$Link = $_SERVER['DOCUMENT_ROOT']."$Folder".$NameToDelete."."."$Type"; //path
@unlink($Link); //DELETE - using @ to not get any errors
echo "Deleted: $Link<br/>"; //Print
}