views:

27

answers:

2

I'm creating a simple caching library in PHP. Currently, when I store a value I create 2 files: One that contains the value and another one to store the creation time. I want a robust solution and I'm not sure how safe it is to use the file date attributes. Do you think is safe to use the file date attribute for expiry time, instead to store it in a separate file?

It will be OS dependent? I want my library to behave the same on windows and linux.

A: 

Under Linux there are three different times associated with a file, the creation time, modification time and access time. Clearly, using the access time would be inappropriate, but the use of the creation time should be ok for your purposes. However, you always run the risk of a user on the system will add, remove or move files in your cache folder.

Another approach is to use one file to store a list or hash of all the file names and their dates. This means that you store each file once and only add one other file to store the expiry information.

You could use the serialize() function to easily store and retrieve the info file as required.

http://php.net/manual/en/function.serialize.php

ar
Good to know. I'm not afraid of other users, but of other processes that might interact with the file date. I'd be more willing to use modify date instead of creation date, so when I have a fresh value to store, I would just rewrite the file.The serialize solution is nice, but I don't think is efficient enough for a big number of files.
php html
+1  A: 

In a small caching function, I am using filemtime function which gives the time when file was changed. It has worked fine on both windows and linux. And don't forget to use clearstatcache() before using filemtime as it's results are cached.

function in_cache($expires_in_secs, $filename){
    clearstatcache(); // Clear file status cache held by PHP

    /* if (file_exists($filename) and  filesize($filename) > 0 ) {  */
    if (file_exists($filename) ) {
        if( time() >= (filemtime($filename) + $expires_in_secs) ){  return false; }
        else { return true; }
    }
    else { return false; }
}
vsr