Sunday, January 16, 2011

Running CodeIgniter from shell on Cronjobs

I am actually tuklifying from the CodeIgniter wiki - just adding my experience - things I faced and solution to the issue.
Steps :
1.Make a directory for your cron scripts. I just used scripts and put it in the same directory that my CI system folder is in.
2. Copy the index.php file from your DOCUMENT_ROOT (the script that normally initiates a connection to CI from a web browser) to the scripts directory, and rename it to something meaningful, such as mailsender.php.
3. Add the following line at the very first line of the mailsender.php:
#!/usr/local/bin/php -q
4. Edit this file and make some slight adjustments. First, we don’t want the script to timeout during execution, so somewhere toward the top we add:
set_time_limit(0);
5. Set the path to the system folder, if it isn’t correct:
$system_folder = "../system";
6. We need to let CI know what controller/method we want to access, and any other URI variables we need. Normally this happens in the URL, so we emulate it by setting PATH_INFO manually:

$_SERVER['PATH_INFO'] = '/mailprocessor/sendmail';
$_GET = ''; // Required for some installations
However, if the config uri protocol is set to REQUEST_URI, then CI doesn’t use PATH_INFO, so instead, emulate REQUEST_URI manually:

$_SERVER['REQUEST_URI'] = '/mailprocessor/sendmail';
7. You create a mailprocessor.php controller (in the application/controllers dir) with a sendmail method, and make it do what it needs to do, load libraries/models/etc, execute them, then exit. What you don’t want to happen is output anything. Just make sure you don’t echo any content to stdout (echo, loading views, etc.) If you are sending emails, you would load a view file, but return the contents to a variable instead of displaying it (pass true as third param), then run through normal procedures for sending emails.
One thing to be aware of regarding security, you probably don’t want anyone accessing /mailprocessor/sendmail from a web browser[In my case I don put the scripts on the web directory- so no need to worry about ], so in the mailprocessor.php controller constructor, you may want to do some kind of check to make sure we are coming from a cron script. Probably the easiest method would be to test the SCRIPT_FILENAME variable:

if($_SERVER['SCRIPT_FILENAME'] != 'mailsender.php')
  exit; 
8.Once everything looks good, add your crontab entry to execute the script, and there you have it! Sample cronjob [from cPanel  can easy do that- you just need to put the script location to run]:
# execute cronjob every day at 2am
00 02 * * * /HOME/myusername/misc/scripts/mailsender.php
My addition : 
8. You need to edit the BASEPATH on the mailsender.php.  You need to put the absolute path instead of relative path.


Original post - You will get some other alternative ways to do the things :)
Update-05/16/2011: On version 2, CodeIgniter has implemented a feature to run sccript from CLI. :)