There are times you need to integrate a 3rd party script into Joomla, without having the modify any core files, while still able to remain within the Joomla framework. A good example is, say, an AJAX request that points to a specific external php file that isn't part of Joomla's MVC. You can do this easy with the following code (in the beginning of the 3rd party script):
define( '_JEXEC', 1 ); //This will define the _JEXEC constant that will allow you to access the rest of the Joomla framework
$joomlaPath = dirname(__FILE__)."/../.."; //The only part you have to change. Make sure the relative part points to your Joomla root
define('JPATH_BASE', $joomlaPath);
require_once( JPATH_BASE.'/includes/defines.php' );
require_once( JPATH_BASE.'/includes/framework.php' );
// Instantiate the application.
$app = JFactory::getApplication('site');
// Initialise the application.
$app->initialise();
// Now you can use all classes of Joomla
$db = JFactory::getDBO();
$doc = JFactory::getDocument();