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.
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);
}
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With