My Personal Blog

Just a spot for my random thoughts.
Category >> Joomla

I found that Joomla's caching feature can cause my server to run out of space quickly unless the admin consistently purges expired cache.  Since Joomla only has a manual mechanism in place to be able to do this, I decided to create a script that can be run by a cron job to handle this for me.

Its quite simple.  First, I load Joomla's framework then simply call the function to purge the cache.

$mainframe = startJoomla();

jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.file');

$cache =& JFactory::getCache('');
$result = $cache->gc();

if ($result) {
    echo 'Expired cache purged.';
} else {
    echo 'Failed to purge expired cache.';
}

function startJoomla()
{
    define('_JEXEC', true);
    define( 'DS', DIRECTORY_SEPARATOR );
    define('JPATH_BASE', dirname(__FILE__) );
    // load joomla libraries
    require_once JPATH_BASE . DS . 'includes' . DS . 'defines.php';
    require_once JPATH_LIBRARIES . DS . 'loader.php';
    jimport('joomla.base.object');
    jimport('joomla.factory');
    jimport('joomla.filter.filterinput');
    jimport('joomla.error.error');
    jimport('joomla.event.dispatcher');
    jimport('joomla.event.plugin');
    jimport('joomla.plugin.helper');
    jimport('joomla.utilities.arrayhelper');
    jimport('joomla.environment.uri');
    jimport('joomla.environment.request');
    jimport('joomla.user.user');
    // JText cannot be loaded with jimport since it's not in a file called text.php but in methods
    JLoader::register('JText', JPATH_BASE . DS . 'libraries' . DS . 'joomla' . DS . 'methods.php');
    JLoader::register('JRoute', JPATH_BASE . DS . 'libraries' . DS . 'joomla' . DS . 'methods.php');

    $mainframe = & JFactory::getApplication('site');
    $GLOBALS['mainframe'] = & $mainframe;
    return $mainframe;
}

I put this code in a file in Joomla's root directory. Then I created a cronjob to have this script ran by PHP every night.  My cronjob looks something like this:

/usr/bin/php /home/username/public_html/purgecache.php

And that's it! Automatic purging.


Tagged in: Untagged