PHP MySQL Query Cache — Best Way

iEntegre
3 min readJun 27, 2022

With this method, you can prevent excessive database usage by Cache the data you query for certain hours.

You can stop Flood attack this way.

Using 3 Functions for Cache Query

Creating Cache

function create_cache($file,$json_data){
global $directory;
global $file_ext;

if (!file_exists($directory)) { mkdir($directory, 0777, true); } // Create Cache Folder if not Exist

$file = $directory.$file.$file_ext; // .cache is custom, change how you want
$json_data = json_encode($json_data);

$f=fopen($file,’w+’);
fwrite($f,$json_data);
fclose($f);
}

Get Cache

function get_cache($file){
global $directory;
global $file_ext;
$file = $directory.$file.$file_ext;
return json_decode(file_get_contents($file),TRUE);
}

Check Cache

function check_cache($file,$time){
global $directory;
global $file_ext;

$time = $time * 60;
$file = $directory.$file.$file_ext;

if (!file_exists($directory)) { mkdir($directory, 0777, true); } // Create Cache Folder if not Exist

if (!file_exists($file) || filemtime($file) < (time() — (int)$time)) {
return false;
} else {
return true;
}
}
  • First we have to Check cache file exist and created (updated) time.

--

--

iEntegre
iEntegre

Written by iEntegre

We teach those who want to learn

No responses yet