So I'm writing a script to delete images from my server. Basically I have a table in my Database which contains a list of buildings and each building has multiple images associated with an id
. I'm saving my images on the server in a single folder and each image has the following naming format:
buildingID_imagename.jpg
. For example, if I have a building with id
=23
, my images in my folder will appear as 23_imagename1.jpg
, 23_imagename2.jpg
, etc.
Now, I know how to delete an image using PHP using the unlink
function. However, to delete all the images, I need to check each file file name one by one, do a split string manipulation, check for the id and then delete. The issue arises when I have like 10000 images in that folder. This becomes an expensive task to do although it will work.
My question, is there a simple way to check the image name and delete it from the folder?
Thanks
EDIT After typing this, I just thought of one possible way. Getting all image links from my database table into an array, loop through it and delete just those. Would that be a good method to do it? Of course, after I get the images into an array, I'm also deleting them from the table.
答案 0 :(得分:1)
Iterate over the dataset, check if file exists and remove the file.
Maybe execute it as a cron job in-case you think there could be thousands of file in this operation.
if(file_exists($fileName)){
unlink($fileName);
}
答案 1 :(得分:0)
您也可以使用
<? array_map ('unlink',glob('23_imagename*.jpg')); ?> // this example deletes all files with .jpg extension that starts with 23_imagename
使用glob功能,您可以应用正则表达式来有效地找到要删除的文件