Created
December 13, 2011 03:01
-
-
Save kijtra/1470314 to your computer and use it in GitHub Desktop.
[PHP] ファイルキャッシュ用関数。関数内の変数にも入れるので、同ページ内でなら何度もファイルを参照しないようにした。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//キャッシュディレクトリ。最後は必ずスラッシュ。 | |
define('CACHE_DIR','path/to/cachedir/'); | |
//ファイルキャッシュ関数。 | |
//引数「$id」と引数「$data」に値が入るとキャッシュ保存。引数「$id」のみで引数「$data」が空ならキャッシュ参照。 | |
//引数「$id」はスラッシュ区切りでキャッシュディレクトリ内にさらにフォルダ作成(デフォルトでは「default」という名前で作成)。 | |
//引数「$data」に「false」を指定すると、該当$idのキャッシュファイルを削除。 | |
//引数「$minute」はキャッシュ時間(分単位)。キャッシュ保存時のみ必要。 | |
function cache($id,$data=NULL,$minute=10){ | |
if($minute<=0 || !defined('CACHE_DIR')){ | |
return $data; | |
} | |
static $cache=array(); | |
if(NULL===$data && isset($cache[$id])){ | |
return $cache[$id]; | |
} | |
$dir=dirname($id); | |
$dir=CACHE_DIR.(('.'==$dir) ? 'default' : $dir); | |
//$id=md5($id); | |
$path=$dir.'/'.basename($id).'.cache'; | |
if(false===$data){ | |
unset($cache[$id]); | |
$status=false; | |
if(is_file($path)){ | |
$status=@unlink($path); | |
@rmdir($dir); | |
} | |
return $status; | |
}else if(NULL===$data && is_file($path)){ | |
$data=unserialize(file_get_contents($path)); | |
if(time()>$data['time']+$data['ttl']){ | |
unlink($path); | |
} | |
return $cache[$id]=$data['data']; | |
} | |
if(!is_dir($dir)){ | |
if(!mkdir($dir,0705,true)){ | |
return $data; | |
} | |
}else if(!is_writable($dir)){ | |
if(!chmod($dir,0705)){ | |
return $data; | |
} | |
} | |
if(!$fp=fopen($path,'w+b')){ | |
return $data; | |
} | |
flock($fp,LOCK_EX); | |
fwrite($fp,serialize(array('time'=>time(),'ttl'=>($minute*60),'data'=>$data))); | |
flock($fp,LOCK_UN); | |
fclose($fp); | |
return $cache[$id]=$data; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment