4

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.

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
Kalle H. Väravas
  • 3,579
  • 4
  • 30
  • 47

2 Answers2

10

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);
   }
}
Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • Ty, works great. I guess there is no neater way, then foreach loop. Though it is still better then readdir() loop. Luckly, I dont have to delete caches manually very often, so optimizing this isn't prio. – Kalle H. Väravas Feb 06 '12 at 17:30
1

You are correct in your guess to search the directory for a matching file name. There are multiple approaches you could take:

readdir the folder in question

glob as suggested by Micheal

You could also get the output of ls {$target_dir} | grep {$file_first_part} and then unlink the resulting string (assuming a match is found).

phatskat
  • 1,797
  • 1
  • 15
  • 32