ThinkPHP implements one key cache clearing method
- 2021-07-04 18:41:27
- OfStack
Many open source cms systems have the function of clearing cache with one key. Cache is generated to reduce the pressure on the server, but at the same time, the existence of cache may also make some data unable to be updated in real time. Therefore, we will implement the function of clearing cache with one ThinkPHP. The code is as follows:
Code executed in the background of ThinkPHP:
// Get the directory to be clear and the absolute path where the directory is located
public function cache(){
//// Front desk ajax get Mode, here is to judge first 1 Under
if($_POST['type']){
// Get the passed value
$type=$_POST['type'];
// To cut the passed value, I use " - "Carrying out cutting
$name=explode('-', $type);
// Get the number of cuts, which is convenient for the following cycle
$count=count($name);
// Loop to call the above method
for ($i=0;$i<$count;$i++){
// Get the absolute path of the file
$abs_dir=dirname(dirname(dirname(dirname(__FILE__))));
// Combined path
$pa=$abs_dir.'indexRuntime';
$runtime=$abs_dir.'indexRuntime~runtime.php';
if(file_exists($runtime))// Judge Does the file exist
{
unlink($runtime);// Perform file deletion
}
// Invoke the method to delete all files under the folder
$this->rmFile($pa,$name[$i]);
}
// Give prompt information
$this->ajaxReturn(1,' Cleanup succeeded ',1);
}else{
$this->display();
}
}
public function rmFile($path,$fileName){// Delete the executed method
// Remove spaces
$path = preg_replace('/(/){2,}|{}{1,}/','/',$path);
// Get the complete directory
$path.= $fileName;
// Determine whether this file is 1 File directories
if(is_dir($path)){
// Open a file
if ($dh = opendir($path)){
// Traverse the file directory name
while (($file = readdir($dh)) != false){
// Per 1 Delete
unlink($path.''.$file);
}
// Close a file
closedir($dh);
}
}
}
Part of the code for the foreground page is as follows:
<script type="text/javascript" src="__PUBLIC__/admin/js/jquery.js"></script>
<script type="test/javascript">
$(function(){
$('#button').click(function(){
if(confirm(" Are you sure you want to clear the cache? ")){
var $type=$('#type').val();
var $mess=$('#mess');
$.post('__URL__/clear',{type:$type},function(data){
alert(" Cache cleanup succeeded ");
});
}else{
return false;
}
});
});
</script>