Skip to content

Clear Cache by POST

Derek Jones edited this page Jul 5, 2012 · 9 revisions

If you want use form->open() without setting the action while still caching the page, this modification will be sure to clear the page's cache once any form values are submitted. Useful for global login forms, especially in conjunction with Slightly Better Caching

[size=4]Output Modification[/size]

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

/**
 * For caching global logins
 *
 * Responsible for sending final output to browser
 *
 * @package        CodeIgniter
 * @subpackage        Libraries
 * @author        Bradford Mar
 * @adapted-from    nmweb(http://codeigniter.com/forums/viewthread/62951/)
 */
class MY_Output extends CI_Output {
    
    /**
     * Update/serve a cached file
     *
     * @access    public
     * @return    void
     */    
    function _display_cache(&$CFG, &$RTR)
    {
    if ($_SERVER['REQUEST_METHOD'] != 'GET') {
        return FALSE;
    }

    $CFG =& load_class('Config');
    $URI =& load_class('URI');
        
    $cache_path = ($CFG->item('cache_path') == '') ? BASEPATH.'cache/' : $CFG->item('cache_path');
        
    if ( ! is_dir($cache_path) OR ! is_writable($cache_path))
    {
         return FALSE;
     }
        
    $uri =    $CFG->item('base_url').
        $CFG->item('index_page').
        $URI->uri_string;

        $filepath = $cache_path.md5($uri);
        
        if ( ! @file_exists($filepath))
        {
            return FALSE;
        }
    
        if ( ! $fp = @fopen($filepath, 'rb'))
        {
            return FALSE;
        }
            
        flock($fp, LOCK_SH);
        
        $cache = '';
        if (filesize($filepath) > 0)
        {
            $cache = fread($fp, filesize($filepath));
        }
    
        flock($fp, LOCK_UN);
        fclose($fp);
                    
        // Strip out the embedded timestamp        
        if ( ! preg_match("/(\d+TS--->)/", $cache, $match))
        {
            return FALSE;
        }
        
        // Has the file expired? If so we'll delete it.
        if (time() >= trim(str_replace('TS--->', '', $match['1'])))
        {         
            @unlink($filepath);
            log_message('debug', "Cache file has expired. File deleted");
            return FALSE;
        }

        // Display the cache
        $this->_display(str_replace($match['0'], '', $cache));
        log_message('debug', "Cache file is current. Sending it to browser.");        
        return TRUE;
    }


}
// END MY_Output Class

/* End of file MY_Output.php */
/* Location: ./system/application/libraries/MY_Output.php */
Clone this wiki locally