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.
There is a very simple and straight forward way of accessing the Codeigniter instance from an external PHP script.
Simply follow the below steps.
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';
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.
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;
}