Bu yöntem ile veritabanında bulunan büyük verilerinize daha hızlı şekilde erişebilir Flood saldırılarını engelleyebilir. Belirlenen saatler için verileri kullanıcılara daha hızlı şekilde sunabilirsiniz.
Cache Query için 3 Fonksiyon oluşturmalıyız.
Cache Dosyası oluştur
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);
}
Cache dosyasından veriyi al
function get_cache($file){
global $directory;
global $file_ext;
$file = $directory.$file.$file_ext;
return json_decode(file_get_contents($file),TRUE);
}
Cache Kontrolü Yapmak
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;
}
}
- İlk olarak Cache dosyası ve saat zaman aşımı kontrol edilir.
- Dosya yok ise veya zaman aşımına uğramış ise Cache dosyası oluştur fonksiyonu ile Çalıştırılan Sorgu verisini dosyaya yazar
- Dosya uzantısı özelleştirilebilir
- Cache dosyası içerisinde saklanan veri isteğinize göre şifreleyebilirsiniz. Biz JSON encode/decode fonksiyonlarını kullandık.
- Zaman süresini istediğiniz gibi özelleştirebilirsiniz.
Koldarın tamamı
// Database Connection with PDO
$localhost = “localhost”;
$db_user = “root”;
$db_pw = “”;
$database = “test”;
$db = new PDO(“mysql:dbname=$database;host=$localhost;”, “$db_user”, “$db_pw”);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Parameters
$file_name = md5(“testcache_query”); // Encrypt File Name with MD5
$file_ext = “.cache”; // File Extension…