Codeigniter
PHP, Web and Mobile development

How to use codeigniter from an external scripts

If you are looking for a way how to use CodeIgniter from an external scripts to access Session’s data, or some other functions, it could results a little tricky.

It depends a lot on your current CodeIgniter’s configuration and expecially if you enabled the output buffering compression.

First steps is to create a variations of the CodeIgniter’s main index.php file to be included by every one of your external scripts.

Starts making a copy of index.php as external.php and edit this new file.

At the top of the file add:

ob_start();

Then in the middle of the file edit the two variables $application_folder and $system_path and make sure you’re using an absolute path instead of a relative one.

Finally at the end of the file add:

ob_end_clean();
header_remove('Content-Encoding');
$CI =& get_instance();
$CI->load->library('session');

I’ve also added more code to make sure that only people that are logged in my codeigniter website can access the pages where i’m including the external.php file; if they are not then the code redirects them to the codeigntier login page:

$username =$CI->session->userdata('user_login_id');

if (strlen($username)==0) {
	$url = $_SERVER['REQUEST_URI'];
	if ($url=='') $url = current_url();
	redirect('/codeigniter_login/?redir='.urlencode($url), 'location', 302);
	exit;
}

Then in your external PHP script just include the external.php file and use the $CI global object to access the whole codeigniter:

	include '../../external.php';
	$this->load->database();
	$this->load->model('user_model', 'MyUsers' );