New to our community ?

Discover a world of possibilities! Join us and explore a vibrant community where ideas flourish and connections thrive.

One of Our Valued Members

Thank you for being part of our community. Your presence enriches our shared experiences. Let's continue this journey together!

Home php codes how to store data in cache file in php

how to store data in cache file in php

how to store data in cache file in php

welcome back to, in this post we will see how to store data in cache file with the help of PHP.
before start this tutorial we should take an overview about cache.
so the very first question in our mind is what is cache , why we store our data in cache file, and what are the benefits to store data in this file.

data caching in php

so basically data caching refers to storing the result of an operation into a file so that future request return faster or we can say that caching is a perfect way to showing repeated data with minimum execution time.

Also Read
How to Install PHP on CentOS.
How to Send Attachment on mail using PHP.

PHP Login Script With Remember me.
Unable to create a directory a wordpress error

How to integrate Razorpay Payment Gateway using PHP.
Change password using javascript, php and mysqli.
Password and Confirm Password Validation Using JavaScript

Check Email is Already Registered in Database using Ajax and JavaScript.
How to hide extension of html and php file.?

in the below code we are creating a cache file with the help of php script and store data into that file and match the execution time of both actions.

<!DOCTYPE html>
$start = microtime(true);
$con  = mysqli_connect("localhost","root","rootroot","testdb");
$cache_file = "cache/index.cache.php";
echo "data fetch from cache file";
	echo "data not file";
	$city = '';
	$find = $con->query("SELECT * FROM cities");
	while($fetch= $find->fetch_assoc())
	 $city .= $fetch['city'];
	$handle =fopen($cache_file, 'w');
$end = microtime(true);
echo round($end-$start,4);

so i have a table in MySQL database with the name of cities and this table have thousands of record in it. so whenever i use select query to fetch all records from the database it takes some time to execution which is more than 5 seconds. i want to reduce this execution time from 5 seconds to 0.005 seconds.

here i am using microtime() which is store the time before the script is start for execution. than we declare a variable of $cache_file and check that the file is exist or not.

so in the very first time this is not exist so we fetch all records from database and store in our $cache_file by using predefined file functions.
now when we perform the same task again it will fetch records from our $cache_file file which will exist this time.

and after the end we store execution time again in our $end variable and than check the difference between start and end time of execution so we got the actual execution time of this script.