Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

file

php

unlink

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.

like image 347
Kalle H. Väravas Avatar asked Dec 22 '22 02:12

Kalle H. Väravas


2 Answers

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);
   }
}
like image 192
Michael Berkowski Avatar answered Dec 24 '22 01:12

Michael Berkowski


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

like image 22
phatskat Avatar answered Dec 24 '22 01:12

phatskat