Jump to content

Delete all files in folder except with certain name


jamiet757

Recommended Posts

I have a script that I want to delete all files in a folder (taken from a database) except for one named thumb1.jpg

 

I have this, but this deletes all the files and a subfolder if there is one. How can I modify it to leave the folder and thumb1.jpg intact, but remove any other files in this folder?

 

if($folder!="" and file_exists($_SERVER["DOCUMENT_ROOT"].site_root.site_upload_directory."/".$folder))

{

  $dir = opendir ($_SERVER["DOCUMENT_ROOT"].site_root.site_upload_directory."/".$folder);

  while ($file = readdir ($dir))

  {

      if($file <> "." && $file <> "..")

      {

        if(is_dir($_SERVER["DOCUMENT_ROOT"].site_root.site_upload_directory."/".$folder."/".$file))

        {

        $dir2 = opendir ($_SERVER["DOCUMENT_ROOT"].site_root.site_upload_directory."/".$folder."/".$file);

            while ($file2 = readdir ($dir2))

            {

              if($file2 <> "." && $file2 <> "..")

              {

              @unlink($_SERVER["DOCUMENT_ROOT"].site_root.site_upload_directory."/".$folder."/".$file."/".$file2);

              }

            }

            @rmdir($_SERVER["DOCUMENT_ROOT"].site_root.site_upload_directory."/".$folder."/".$file);

        }

        else

        {

            @unlink($_SERVER["DOCUMENT_ROOT"].site_root.site_upload_directory."/".$folder."/".$file);

        }

      }

  }

  @rmdir($_SERVER["DOCUMENT_ROOT"].site_root.site_upload_directory."/".$folder);

}

 

}

That seems good, so in your example, it will delete any file that is not named "index.php", and it will leave the folder intact?

 

The only problem is, the folders are different, they are taken from the database depending on which entry I am deleting. How can I incorporate that into your example?

Well no, actually that script deletes the folders too.

But you can make the script more advanced, and check if the file is written like a file name like this:

 

if (!preg_match("/^[^.].*[^.]/$", $file)) // If file doesn't match pattern skip.
continue;

 

Note: This wont work if the folder is named something like "my.folder" since this is name based.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.