Reputation: 1109
I have an admin system which adds profile pages dynamically - and part of that adds images to a directory. When I add the images they all have the name format like 12_1.jpg, 12_2.jpg, 32_1.jpg, 32_9.jpg where the number before the underscore is the id $cid
and the number after the underscore is the image number.
I'm trying to find a way to list the images on the edit-images.php page with an option to delete them (maybe a link next to the image name, or another way that is better).
Here is the code to find the images I need to have the option of deleting:
if ($handle = opendir('../images/company')) {
while (false !== ($entry = readdir($handle))) {
if (substr(basename($entry), 0, 2) == $cid) {
echo $entry . "<br>";
}
}
closedir($handle);
}
How would I go about deleting specified images from here? Any help would be appreciated.
Upvotes: 0
Views: 119
Reputation: 9142
Why are you scanning the directory for the file? You can check if the file exists and delete it instead. For example:
$files = glob("../images/company/$cid_*.jpg");
foreach($files as $file) {
if(file_exists($file)) unlink($file);
}
This will unlink all files in ../images/company
with the name starting with 123_
for example and ending in .jpg
(you can provide more extensions by using GLOB_BRACE
parameter)
Upvotes: 1