Category Archives: PHP

Deleting Cached Web Page by URI in CodeIgniter

PROBLEM

CodeIgniter contains a wonderful feature that allows me to cache web pages to speed up the page loading. The problem is there’s no easy mechanism for me to delete specific cached web pages, especially after I have updated the page contents. I have sucky two choices:-

  • Wait for the cache to expire by itself, which can be an excruciating wait since I tend to cache my web pages for a month.
  • Delete all cached files under application/cache.

I always do the latter even though I hate this approach.

SOLUTION

After poking around the web, it looks like @danmurf had written an Core Output extension that allows me to delete the cache by URI, which is exactly what I want.

The installation is pretty straightforward. To test it out, I used @philsturgeon’s REST support to create a simple controller to do so:-

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

    require(APPPATH . 'libraries/REST_Controller.php');

    class Delete_cache extends REST_Controller
    {
        public function __construct()
        {
            parent::__construct();
        }

        public function index_post()
        {
            $uri = $this->post('uri');
            $statusCode = $this->output->clear_path_cache($uri) ? 200 : 404;
            $this->response(NULL, $statusCode);
        }
    }

When I do a POST on http://localhost:8888/api/delete_cache?uri=/meow-meow, I’ll get either a 200 if the cached file is successfully deleted, or a 404 if the cached file is not present.

Works like a charm.