本篇內(nèi)容主要講解“php緩存機(jī)制的實(shí)現(xiàn)方式”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“php緩存機(jī)制的實(shí)現(xiàn)方式”吧!
復(fù)制代碼 代碼如下:
<?php
class Cache
{
private $dir = "data/cache/";//定義緩存目錄
private $key='c_a_sss'; // 文件名md5加密密鑰
function set_dir($dirpath)
{
$this->dir=$dirpath;
$this->make_dir($this->dir);
}
function read($key,$minutes=1)
{
$filename=$this->get_filename($key);
if($datas = @file_get_contents($filename))
{
$datas = unserialize($datas);
if(time() - $datas['time'] < $minutes*60)
{
return $datas['data'];
}
}
return false;
}
function write($key,$data)
{
$filename=$this->get_filename($key);
if($handle = fopen($filename,'w+'))
{
$datas = array('data'=>$data,'time'=>time());
flock($handle,LOCK_EX);
$rs = fputs($handle,serialize($datas));
flock($handle,LOCK_UN);
fclose($handle);
if($rs!==false){return true; }
}
return false;
}
function clear_all()
{
$dir=$this->dir;
$this->del_file($dir);
}
private function get_filename($key)
{
return $this->dir.$key.'_'.md5($key.$this->key);
}
private function make_dir($path)
{
if (! file_exists ( $path ))
{
$this->make_dir ( dirname ( $path ) );
if (! mkdir ( $path, 0777 ))
die ( '無法創(chuàng)建緩存文件夾' . $path );
}
}
private function del_file($dir)
{
if (is_dir($dir))
{
$dh=opendir($dir);//打開目錄 //列出目錄中的所有文件并去掉 . 和 ..
while (false !== ( $file = readdir ($dh))) {
if($file!="." && $file!="..") {
$fullpath=$dir."/".$file;
if(!is_dir($fullpath)) {
unlink($fullpath);
} else {
$this->del_file($fullpath);
}
}
}
closedir($dh);
}
}
}
$cache = new cache();
$cache->set_dir('data/cache_dir/');
$data=$cache->read('sys',1);
if(empty($data))
{
$data=array('aa'=>1111,'bb'=>2222,'date'=>date('Y-m-d H:i:s'));
$cache->write('sys',$data);
}
print_r($data);
到此,相信大家對“php緩存機(jī)制的實(shí)現(xiàn)方式”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)建站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
網(wǎng)頁名稱:php緩存機(jī)制的實(shí)現(xiàn)方式-創(chuàng)新互聯(lián)
網(wǎng)頁網(wǎng)址:http://www.rwnh.cn/article26/dosgjg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)網(wǎng)站建設(shè)、靜態(tài)網(wǎng)站、虛擬主機(jī)、App開發(fā)、Google、品牌網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容