这是我的缓存解决方案:
<?phpdefine('CACHE_FILE', 'mycache.tmp');define('CACHE_TIME', 20); // 20 seconds (for testing!)define('IMG_COUNT', 30);define('IMG_DIR', '../public/wp-content/uploads/2012/01');function LoadListFromCache($cacheFile, $cacheTime){ if ( file_exists($cacheFile) ) { $fileHandle = fopen($cacheFile, 'r'); if ( !$fileHandle ) return false; // Read timestamp (separated by "n" from the content) $timestamp = intval( fgets($fileHandle) ); fclose($fileHandle); // Expired? if ( $timestamp+$cacheTime > time() ) return false; else { // Unserialize the content! $content = file_get_contents($cacheFile); $content = substr( $content, strpos($content, "n") ); $list = unserialize($content); return $list; } } return false;}function SaveListToCache($cacheFile, $list){ $fileHandle = fopen($cacheFile, 'w'); if ( $fileHandle === FALSE ) return false; fwrite($fileHandle, time()); fwrite($fileHandle, "n"); fwrite($fileHandle, serialize($list)); fclose($fileHandle); return true;}function GenerateList(){ $a = array(); $dir = IMG_DIR; if ($handle = opendir($dir)) { while (false !== ($file = readdir($handle))) { if (preg_match("/.png$/", $file)) $a[] = $file; elseif (preg_match("/.jpg$/", $file)) $a[] = $file; elseif (preg_match("/.jpeg$/", $file)) $a[] = $file; } closedir($handle); } SaveListToCache(CACHE_FILE, $a); return $a;}function GetRandomImages($list, $count){ $listCount = count($list); $randomEntries = array(); for ($i=0; $i<$count; $i++) { $randomEntries[] = $list[ rand(0, $listCount) ]; } return $randomEntries;}// This pre will execute the other functions!$list = LoadListFromCache(CACHE_FILE, CACHE_TIME);if ( $list === FALSE ){ $list = GenerateList();}$images = GetRandomImages($list, IMG_COUNT);foreach ($images as $image){ echo '<img src="', IMG_DIR.DIRECTORY_SEPARATOR.$image, '" />';}


