簡單的php緩衝類分享

來源:互聯網
上載者:User

 這篇文章主要介紹了一個php緩衝類,檔案名稱使用md5加密,大家參考使用吧

代碼如下:<?phpclass 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 ( '無法建立快取檔案夾' . $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); 
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.