Simple PHP script to cache data using serialize

PHP has a wonderful function by the name of serialize which you can use to generate a storable version of a simple variable, array or an object and store it in a text file for later retrieval. This function can help you to cache the data on your web page for as long as you want without needing to connect to your database to retrieve the same information over and over again. Let’s look at an example of a simple script which checks whether a cached version of the records exist or not. If it exists then it will display the data from there otherwise it will connect to the database, fetch the records and then cache them..

// Check for cached version of the file
if (file_exists("cache/cache_file.txt")) {
// If it exists then fetch the data from there
$f = fopen("cache/cache_file.txt","r");
$str = fread($f, filesize("cache/cache_file.txt"));
fclose($f);

// Using the unserialize function to get the original data
$arr = unserialize($str);
}
else {
// If not then connect to the database and then cache it
$sql = " select book_id, book_name from books order by book_name asc ";
$rs = mysql_query($sql);
$arr = mysql_fetch_array($rs, MYSQL_ASSOC);

// Caching the data using serialize
$f = fopen("cache/cache_file.txt","w");
fwrite($f, serialize($arr));
fclose($f);
}

// Do what you want with the $arr variable

You can tweak the above code according to your requirements.

Comments?

Please follow and like us:
error

Be the first to comment

Leave a Reply

Your email address will not be published.