How to disable browser cache easily for particular, individual and separate function and controller in Codeigniter
This article we are going shows how to disable browser cache easily for particular, individual and separate functions and controller in Codeigniter. We face some kind of problems in real life when browser caches the data particularly when there are session data. Though we destroy the session still we can access some data on the browser because of browser stores data into its cache.
So we can disable browser cache easily using Codeigniter or other server-side technologies using the cache-control technique.
First step Extending Core Class
We will create a core class MY_Cacheoff which extends CI_Cacheoff and put the core class under “application/core” containing the following code.
Whenever we want to extend Codeigniter’s core class then we need to start with MY_ because this is the default prefix for our custom class name.
The prefix is configured in the config.php file under application/config folder. If you want to have different prefix then you can change it in config.php file.
When you will call your core class from other class, then you drop the prefix name from the class. For example, if you create a core class MY_Cacheoff then simply call your class as output from another class or Controller or function.
We will create here our own core class called MY_Cacheoff under application/core folder with the below source code.
In the above code we have set HTTP headers with past date in order to disable browser cache. So it means that the headers already expired on a particular date.
We have also specified max-age=0 to indicate that cache lives only for 0 seconds, i.e., no-cache.
We also specified cache-control with no-cache, no-store and must-revalidate to tell the browser that it can cache but before that it must validate with the server.
Step 2 Disabling Cache
Now, all you have to do is call the method with the following code before you send any data to the browser.
Generally, the best place is to put into the controller’s constructor for pages where user validation is required.
Let’s say we want to disable cache for the login page so that when a user already logged in and by mistake, he/she clicks the browser’s back button then he/she should not visit the login page again.
In the above code, we call the method disable_cache() inside the controller’s constructor to disable browser cache easily in Codeigniter.
You can write other methods as usual in the controller for other business requirements.
You have to call this disable_cache() method in those controllers constructors, where you don’t want your browser to cache the data.