Page 1 of 1

Caching in php

Posted: Wed Feb 14, 2007 5:57 am
by Darla
Hello

I am wondering what is the best method for caching variables or arrays in php (for 3 minutes)? Or is it better to cache the whole page where these variables are? I see there are a few methods out there and I am uncertain what to use. Therefore I am wondering if someone here knows a simple/effective way of doing this as it is kind of a minor application I am building. (I can use a mysql table for temporary storage, will this be considered good caching even though it is not the traditional way of caching?)

Have a nice day!

Darla

Posted: Wed Feb 14, 2007 6:15 am
by Jenk
Depends on where your sourcing the data from (and what processing is involved).. if it is other tables, there is no point caching in tables.

Traditionally caching in PHP refers to caching output from dynamic pages, as opposed to regenerating the page at every request.

Posted: Wed Feb 14, 2007 6:32 am
by Darla
Could you give me an example of what you mean by "caching output from dynamic pages"?

I am fetching the data from a feed. I will maximum fetch data from the feed every three minutes, thus the caching. So far my application fetch data from feed and puts it into 6 variables/one array. Then these values needs to be cached for three minutes before fetching new data from the feed.

Darla

Posted: Wed Feb 14, 2007 7:01 am
by Jenk
Google searching for "PHP Caching" will provide many links to caching tutorials and papers. :)

Here is a brief (and untested) example:

Code: Select all

<?php

$cachefile = '/tmp/page12345.html';

// if the cache file exists, and the cache is younger than 1 hour, use it.
if ( file_exists($cachfile) && (now() - filemtime($cachefile)) < 3600 )
{
    echo file_get_contents($cachefile);
}
// cache either doesn't exist, or is older than 1 hour, regenerate.
else
{
    ob_start();

    // do your pages bits here..

    $cachecontent = ob_get_contents();

    file_put_contents($cachefile, $cachecontent);

    ob_end_flush();
}

?>

Posted: Wed Feb 14, 2007 8:25 am
by Darla
Thanks for this, I'll test it out. Here i see an entire file is cached. I thought of doing it like this alternatively (using a table):

- Have a table with 6 values + a timestamp
- Upon request: do a comparison in php between current time and the timestamp in db table
- If the diff is less than 3 minutes -> display the data from the db table
- If the diff is more than 3 minutes -> fetch new data from feed and insert new value to db table after deleting the currect record

Which would you then prefer? The example you gave me with file or the suggestion I described above using the table?

Darla

Posted: Wed Feb 14, 2007 9:30 am
by Jenk
I'd prefer the full output caching as per my example, personally. However your suggestion of using tables to store cached data is not a bad solution - though because the timeout for the cache is only 3minutes, I would probably stick with using a full file.