How to use Codeigniter from an external PHP script


2

Hello developers,

I have a requirement that I must access the functionality of Codeigniter framework from another core PHP script. In my case, Codeigniter based website exists in the root folder of server while the other PHP script is inside a subdirectory.

Is it even possible to use Codeigniter functionality outside of the framework? Any help will be highly appreciated.

Thanks.


Share
asked 19 Sep 2019 11:40:33 AM
junaidakhtar

No comment found


Answers

1

There is a very simple and straight forward way of accessing the Codeigniter instance from an external PHP script.

Simply follow the below steps.

Step 1:-

Create a duplicate copy of Codeigniter's root index.php file and name it as external.php

Open external.php file.

Now you need to do some minor changes here.

Replace
$system_path = 'system';
with
$system_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'system';

And replace
$application_folder = 'application';
with
$application_folder = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'application';

Step 2:-

Now open the PHP file of external script from where you want to access the Codeigniter instance.

Here you need to define a constant which will be used inside default controller of Codeigniter to determine whether the Codeigniter is accessed from external script or not.
define("CODEIGNITER_EXTERNAL_ACCESS", true);

After that add below code:

ob_start();
require_once '../external.php'; // File to access Codeigniter from external script.
ob_get_clean();
$main_codeigniter = $CI;

Now $main_codeigniter variable contains the Codeigniter instance which can be used to access the functionality of Codeigniter from external script.

Step 3:-

This step is very important because you have to write a conditional statement inside your default controller of Codeigniter so that it should not display anything if the Codeigniter is accessed from an external script.

We can do this with the help of a constant which we have defined in Step 2.

Copy below code and write it inside your __construct() and index() functions of default controller. Put the code at the top of these functions.

Note: If the name of your default method is something else than the index() function then you must use below code inside that method.

if (defined('CODEIGNITER_EXTERNAL_ACCESS'))
{
    return;
}

Share
furqan - Profile picture
answered 19 Sep 2019 02:21:05 PM
furqan

Amazing! Thanks for the quick reply sir. Your answer is really helpful. — junaidakhtar 19 Sep 2019 02:30:20 PM
You are welcome bro. :) — furqan 19 Sep 2019 02:33:02 PM


You must log in or sign up to answer this question.