简体   繁体   中英

Recursively delete files with different names within directories - PHP

I'm using a script called ELGG. It allows my members to upload images to 4meg, but automatically reduces them to a defined size (700px wide or high). Unfortunately the huge images remain in the directories and this is choking my server. Several small images are produced in the process depending on whether it's a photo or avatar and I have to be careful I leave the right ones behind. It's not a busy site and I can run a small script weekly.

Here's where it get's tricky. The files I need to save are strangely numbered:

###large.jpg
###medium.jpg
###small.jpg
###tiny.jpg
###topbar.jpg
largethumb#####.jpg
smallthumb#####.jpg
thumb#####.jpg

The numbering ### seems to be random and varies from 2 digits to 20.

The files I need to delete will be names issued by my members but will also contain numerals issued by Elgg.

The script doesn't have to be fancy. It just needs to delete all files except the ones above in all sub directories.

Hopefully someone can help and thanks in advance.

You can use scandir to list All files inside the Directory. Then, You can use preg_match to just select the files matching Your conditions. Finally, unlink will delete the file You pass as argument.

You can also use preg_filter also instead of preg_match.

Loop with something like this into the directory:

$image = "pin987414578.png";
$delete = "pin987414578.png"; //keep original name to delete
$image2 = preg_replace("/[^a-z,A-Z.]/", "", $image);
if($image2=="large.png" ||$image2=="medium.png" ||$image2=="small.png" ||)
{
unlink($delete)
}

this sample= result: pin.png

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