Advertisement
Google Ad Slot: content-top
CodeIgniter Page Caching
Page Caching in CodeIgniter is a simple way to improve performance and speed of your website.
When caching is enabled, CodeIgniter saves the output of a page request as a static file.
Next time when the same page is requested, CodeIgniter will serve the cached version instead of processing the entire controller and database queries again.
This reduces:
- Database load
- Server processing time
- Page load time
๐น How Page Caching Works
- You enable caching in your controller method.
- The page output is saved as a cache file inside:
application/cache/
- Next time the same page is requested, CodeIgniter serves the cached file.
- After the cache expires, CodeIgniter will regenerate it automatically.
๐น Enabling Page Caching
Use the cache() method in your controller:
class Welcome extends CI_Controller {
public function index()
{
// Enable cache for 10 minutes
$this->output->cache(10);
$this->load->view('welcome_message');
}
}
โ Here, the page output will be cached for 10 minutes.
๐น Clearing Cache for a Page
To clear cache for a specific URL, you can manually delete the cache files inside:
application/cache/
Or use helper functions (in CI3 you often write a custom function for cache removal). Example:
$this->output->delete_cache('welcome/index');
๐น Cache File Location
Cached files are stored in:
application/cache/
Make sure this folder is writable by the server.
๐น Things to Remember
- Page caching works per URL.
- If you pass query strings like
?id=1and?id=2, they will generate different cache files. - Donโt use caching for dynamic pages like user dashboards or shopping carts.
- Best used for static content pages like blog articles, about us, contact pages, etc.
Example: Caching a Blog Page
class Blog extends CI_Controller {
public function article($id)
{
// Cache for 30 minutes
$this->output->cache(30);
$data['article'] = $this->db->get_where('articles', ['id' => $id])->row();
$this->load->view('blog_view', $data);
}
}
๐ Now, when a user visits the blog page, it will be cached for 30 minutes.