Search code examples
phpfileunlink

How to unlink() by its name without knowing the file extention?


In short

We have a a file called clients.(unique parameter). And now we want to unlink() it, but as we don't know the file extension, how do we succeed?

Longer story

I have a cache system, where the DB query in md5() is the filename and the cache expiration date is the extension.

Example: 896794414217d16423c6904d13e3b16d.3600

But sometimes the expiration dates change. So for the ultimate solution, the file extension should be ignored.

The only way I could think of is to search the directory and match the filenames, then get the file extension.


Solution

  • Use a glob():

    $files = glob("/path/to/clients.*");
    foreach ($files as $file) {
      unlink($file);
    }
    

    If you need to, you can check the filemtime() of each file returned by the glob() to sort them so that you only delete the oldest, for example.

    // Example: Delete those older than 2 days:
    $files = glob("./clients.*");
    foreach ($files as $file) {
       if (filemtime($file) < time() - (86400 * 2)) {
         unlink($file);
       }
    }