note 48000 deleted from function.serialize by aharvey
| From: | aharvey@php.net | Date: | Tue, 06 Nov 2012 02:06:39 +0000 |
| Subject: | note 48000 deleted from function.serialize by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-191754@lists.php.net to get a copy of this message | ||
Note Submitter: corey at eyewantmedia dot com
----
If this helps anybody, I was looking for a few quick calls to cache stuff to files. I settled on the
below functions. By the way, if I am doing something stupid here, I'd appreciate some comments
on that also. Anyway, on with the code:
First, the usage:
//Use:
$var = tuncache('MyCacheName');
if (is_null($var)) {
$var = 'a really expensive process';
$check = tcache('MyCacheName', $var, '+25 minutes');
if (is_null($check)) {
die('I need to reset my permissions or get a bigger hard drive');
}
}
//use $var now
Now, the functions:
//uses strtotime to decide how long to cache $cacheVar based on $lifespan
//so anything but a timestamp works. +1 day works, 09/14/2010 works, etc
function tcache($cacheName, $cacheVar, $lifespan=null) {
if (!is_null($lifespan)) { //a lifespan was provided
if (strpos($lifespan, '+') === 0 || strpos($lifespan, '-') === 0) {
//Have to do this to counter for bug in php5 to
//properly evaluate now to do the date math
$endTime = strtotime(date('m/d/Y H:i:s') . ' ' .$lifespan);
} else {
//we can safely use anything else I think
$endTime = strtotime($lifespan);
}
} else {
//cache forever (forever being ten years) until manually deleted
$endTime = strtotime(date('m/d/Y H:i:s') . ' +10 years');
}
$cVal = serialize($cacheVar);
$file = tFindcache($cacheName);
$result = true;
$f = fopen($file, 'w');
if ($f === false) {
$result = null; //barf if we can't open the file
} else { //write the cache
fwrite($f, $endTime . "\n");
fwrite($f, $cVal);
fclose($f);
}
return $result;
}
function tuncache($cacheName) {
$file = tFindCache($cacheName);
if (is_readable($file)) {
//open file
$f = fopen($file, 'r');
$time = time();
$expTime = trim(fgets($f));
//check time
if ($time > $expTime) {
//It expired
$result = null;
} else {
//Read it and unserialize it
$data = fread($f, filesize($file));
$result = unserialize($data);
}
} else {
//barf
$result = null;
}
return $result;
}
//just to set a few options for setting where to save stuff
function tFindCache($cacheName) {
if (isset($_ENV['PHP_CACHE_PATH'])) {
$cachePath = $_ENV['PHP_CACHE_PATH'];
} else if (isset($_SERVER['PHP_CACHE_PATH'])) {
$cachePath = $_SERVER['PHP_CACHE_PATH'];
} else {
$cachePath = './'; //Potential danger here
}
$cachePath .= 'PHP_CACHE_' . $cacheName . '.cache';
return $cachePath;
}