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

  1. You enable caching in your controller method.
  2. The page output is saved as a cache file inside:
application/cache/
  1. Next time the same page is requested, CodeIgniter serves the cached file.
  2. 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=1 and ?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.


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
ยฉ Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.