Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php script to delete file names not matching a dynamic text file

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);

    }

}

>Solution :

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);
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading