John Davidson

loops - Combine Two File Deletion Functions Into One With A Wildcard - PHP

0 comments
Message:


I have a folder that contains two sizes of avatar image (50x wide and 250px wide). I'm currently deleting them with two foreach functions when a new profile avatar is uploaded.


In the code below the $destinationFolder is the directory the files are in, the '250-' is a string prefix for the filename based on image size and $db_profileImage is the filename that is assigned when the image is originally uploaded (this includes the file ext e.g. jpg/png). The image is also deleted from a MySQL database via a PDO Prepared Statement.


// DELETE PREVIOUS PROFILE IMAGES FROM FOLDER WHEN NEW IMAGE IS UPLOADED
foreach(glob($destinationFolder . '250-' . $db_profileImage) as $i){
unlink($i);
}
foreach(glob($destinationFolder . '50-' . $db_profileImage) as $i){
unlink($i);
}

// an example filename would be:
'50-613a9f679a072.png'

I also need to create this functionality on my main images folder which has 5 different sizes of image that are produced when an image is uploaded (and thus will need to be removed when deleted), and I would like to replace the size prefix with a wild card (which I think is the best way to approach this?). In other words replace the '250-' and '50' with a wildcard character and have one foreach function.


Any help/advice much appreciated on a) if I'm approaching this correctly, and if so the best way to incorporate the 'wildcard' character.



My Answer:
You can achieve this by using the `*` wildcard character in the `glob` function to match any characters in place of the size prefix. Here's how you can combine the two file deletion functions into one with a wildcard:

php
// DELETE PREVIOUS PROFILE IMAGES FROM FOLDER WHEN NEW IMAGE IS UPLOADED
foreach(glob($destinationFolder . '*-' . $db_profileImage) as $i){
unlink($i);
}


In this code snippet, the `*` wildcard character will match any characters in place of the size prefix, allowing you to delete all files with any size prefix followed by the `$db_profileImage` filename.

Make sure to test this code thoroughly to ensure it works as expected before implementing it in your production environment.

Rate this post

3 of 5 based on 2836 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us