//如果文件生产失败,多半是当前文件没有创建文件与目录的权限,请给予权限即可 //这里调用缓存,使用方法类是TP的S方法 if(!$cate = CacheHtml('IndexModelPlodesadasdw')){ $cate = array('asdsad'=>'asdsad','asfqwf'=>'qwfqwf'); //这里生成缓存 CacheHtml('IndexModelPlodesadasdw',100,$cate); } print_r($cate); /** * [CacheHtml 缓存方法] * @E-mial [email protected] * @TIME 2017-10-11 * @WEB http://blog.iinu.com.cn * @param [type] $cache [缓存名称] * @param [type] $cachetime [缓存时间] * @param [type] $cachedata [缓存的数据] * @param [type] $cachepath [缓存的路径] * @param [type] $cachetype [缓存类型] */ function CacheHtml($cache,$cachetime=5,$cachedata='',$cachepath='',$cachetype=1){ //检查文件名是否存在特殊字符 $cache = preg_match("/_/",$cache) ? '1' : $cache; if($cache == 1){ return false; } //缓存路径 $cachepath = $cachepath == '' ? $_SERVER['DOCUMENT_ROOT'] : $cachepath; //缓存目录 $catalog = 'cache'; //文件后缀 $fileSuffix = '.php'; //检查缓存目录是否存在 is_dir($catalog) or @mkdir($cachepath.$catalog, 0777); //遍历查找该目录下所有文件 $ArrayFile = listDir($cachepath.$catalog); //把获取掉的文件后缀删除 if(!empty($ArrayFile)){ foreach($ArrayFile as $k=>$v){ //只匹配后缀为.php的 if(mb_substr($v,-4) == '.php'){ //拆分文件名 $getFileNameTime = explode('_',$v); //获取当前文件的到期时间 $getFileEndTime = $getFileNameTime[count($getFileNameTime)-2]; //把缓存时间到期的文件删除 if(time() >= $getFileEndTime){ //删除到期文件 unlink($cachepath.$catalog.'/'.$v); return false; } //获取文件名 $getFileName = $getFileNameTime[count($getFileNameTime)-1]; //当前文件名等于传入文件名时 if($getFileName == $cache.$fileSuffix){ //合并文件名 $cacheName = $v; } } } } //检查缓存是否存在 if(is_file($cachepath.$catalog.'/'.$cacheName)){ //缓存存在则打开 $fileopen = fopen($cachepath.$catalog.'/'.$cacheName,'r'); //读取缓存的数据 $fileData = fread($fileopen,filesize($cachepath.$catalog.'/'.$cacheName)); //将缓存的数据返回 $fileData = json_decode($fileData,true); }else{ if($cachetime==5 || empty($cachedata)){ return false; } //判断数据类型 if(is_string($cachedata)){ //数据为字符串将数据组合为数组并且转换为JSON $jsonData = json_encode(array($cachedata)); }else{ //数据为数组将数组转换为JSON $jsonData = json_encode($cachedata); } //组合文件名 $cacheName = time().'_'.(time()+$cachetime).'_'.$cache.$fileSuffix; //缓存不存在则创建 $fileopen = fopen($cachepath.$catalog.'/'.$cacheName,'w+'); //将缓存的数据写入文件 $fileData = fwrite($fileopen,$jsonData); } //关闭 fclose($fileopen); return $fileData; } /** * [listDir 遍历目录下所有文件] * @E-mial [email protected] * @TIME 2017-10-11 * @WEB http://blog.iinu.com.cn * @param [type] $dir [要遍历的路径] * @return [type] [description] */ function listDir($dir) { if(!is_dir($dir)) { return false; } if(!$dh = opendir($dir)) { return false; } while(($file = readdir($dh)) !== false) { if((is_dir($dir."/".$file)) && $file!="." && $file!="..") { $arr[] = $file; listDir($dir."/".$file."/"); } else { if($file!="." && $file!="..") { $arr[] = $file; } } } closedir($dh); return $arr; }
本文出自:新太潮流网络博客