Home > Software engineering >  php script to delete file names not matching a dynamic text file
php script to delete file names not matching a dynamic text file

Time:06-04

I have created a text file (images.txt) located in /home/users/images.txt, the File contain names of jpeg files. for example:

1.jpeg

12.jpeg

33.jpeg

This file is updated regularly and new image filenames are added

I am looking for a php script that can help in reading the filenames from the .txt and deleting any files from /home/user/images/ directory that does not match the filenames in the .txt file

I have tried the below code and cant get it to work

$array = explode("\n", file_get_contents('/home/user/images.txt'));

$directory = "/home/user/images/";

$files = glob($directory . "*.*");

foreach($files as $file)
{
 
   if (!in_array($file, $array)) {
       unlink($directory . $file);

    }

}

CodePudding user response:

The names returned by glob() include the directory prefix, but the names in $array don't have them. You need to remove the prefix before searching, and you don't need to add it when calling unlink().

$array = file('/home/user/images.txt', FILE_IGNORE_NEW_LINES);
$directory = "/home/user/images/";
$files = glob($directory . "*.*");

foreach($files as $file)
{
   if (!in_array(basename($file), $array)) {
       unlink($file);
   }
}
  • Related