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
Caching in php
Moderator: General Moderators
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
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
Google searching for "PHP Caching" will provide many links to caching tutorials and papers. 
Here is a brief (and untested) example:
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();
}
?>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
- 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