Sometimes one needs to access Joomla’s functions and variables from an external script. Typically one should write a Joomla extension to do so but maybe you want something done quick, or you just need a little integration to another system, e.g. I’ve often had the need to grab the name or id of a user and write a record to another database to link them, find what page a user came from, check their access level, etc, etc,
Obviously just having the code in Joomla’s folder isn’t enough – the application needs to be loaded and looking through the code to find the correct way of doing so isn’t immediately obvious — Joomla contains thousands of files after all. Not to worry, they make it quite easy. Just add the following code to your php script file and get access to Joomla’s goodness.
define( '_JEXEC', 1 );
define( 'JPATH_BASE', "/var/www/mywebsite" );
define( 'DS', '/' );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
require_once ( JPATH_BASE .DS.'libraries'.DS.'joomla'.DS.'factory.php' );
$mainframe =& JFactory::getApplication('site');
From there on in you will be able to access various Joomla variables, e.g. use the following to get the user object for the currently logged in user – assuming this script is called in a link from Joomla.
$theUser =& JFactory::getUser();
Or use other JFactory functions like getConfig() or getSession()
Should work in Joomla 1.5 upwards. A simple way to add some simple Joomla integration to your scripts.