Tuesday, 2 September 2008

Deleting unwanted images of the server.

What I wanted to do was to write a script that after loading an image would then check the image folder for any unwanted image, which would then be deleted.

So first of all I wanted to get a list of files in the folder - for this we need to use readdir - see http://uk3.php.net/manual/en/function.readdir.php

function list_folder($folder){

$dh = opendir($folder);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
return $files;



//Then i needed to make an array of a list of images that I do want to keep.

//my list looks a bit like this

$images_wanted_array[0] = $row['img1'];
$images_wanted_array[1] = 'thum'.$row['img1'];

/* once have these two list then I run a foreach inside a foreach statement.
So each file gets checked against the list of wanted files. If theres a match I get the result '$success'. After checking the whole wanted list I do a check for any succesful matches and only delete if there aren't any.
Here's the function I wrote.

function deleting_unwanted_images($images_array, $wanted_array, $path){ // this function takes an array of images and they aren't on the wanted_array list they will be deleted.

foreach ($images_array as $f) {
foreach ($wanted_array as $i){
if ($f == $i){
$success = TRUE;
if (!$success){
$file_to_delete = $path.$f;
echo '
The file'.$f.' - has been deleted
}else {
echo '
There has been a match so we are going to keep the file '.$f.'


No comments: