Running CodeIgniter from Cron/CLI

Many of us faced the problem of running CodeIgniter controllers from Cron or from Command Line. usually we write the following codes to run a php file from cron/CLI.

php /var/www/path/to/your/script

but if we give CodeIgniter Controller path here it will not work since CodeIgniter will fail to initialize its core classes. A work around of this is running the script using CURL

curl http://yourwebsite/controllername

the problem with the above command is that it takes too much CPU resources .

Today my collegue Hasan showed me a nice way of doing it, just write the following codes in a php file in your root folder. here is the way to go

<?
$_GET[“/external/do_cron”] = null;
require “index.php”;
?>

note: here “external” is the controller name and “do_cron” is the function name that you want to execute.

now save this file to any name you want (eg. mycron.php) and run the script using

php /var/www/path/to/script

[here it is php /var/www/mywebsite/mycron.php]

if the above code does not work, you can try the following one. (thanks to sucio)

$_SERVER[“REQUEST_URI”] =”external/do_cron”;
require “index.php”;

13 thoughts on “Running CodeIgniter from Cron/CLI

Leave a Reply

Your email address will not be published. Required fields are marked *