r4ccoon r4ccoon - 2 years ago 58
PHP Question

Finding if a dynamic filename exists among thousands of files

I am writing a cache module in PHP. It tries to write a cache with a

as a filename.

I don't have problem with writing the cache.

The problem is, I do a foreach loop to get the cache that I want.

This is the logic that I use for getting the cache:

foreach ($filenames as $filename){
if(strstr($filename,$cachename)){//if found

But when it tries to get and read the cache, it slows the server down. Imagine that I have 10000 cache files in a folder, and I need to check for every file in that cache folder.

In other words, I write the cache file with this format
. For example:

in a folder

When I want to get the cache, I only pass
and check recursively on that folder.
If I find something with that needle on a file name, display it, and break.

But checking recursively on a 10000 files in a folder is not a good thing, right?

What's the best way of doing this?

Answer Source

Do not store the timestamp as part of the filename, but store it in the file together with the cached content in some format that makes sense to you. For example:

File /cache/cache_function_random_news:

stored content

The first line of the file contains the timestamp, which you can read when needed, e.g. when cleaning the cache periodically. The rest of the file contains the cached content. Another possibility would be to use serialized arrays. Either way, this makes it trivial to read the cache:

if (file_exists('cache/cache_function_random_news')) ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download