How to execute a CakePHP controller's action from a cron job
First copy webroot/index.php to webroot/cron_scheduler.php. Replace everything below require CORE _PATH . ‘cake’ . DS . ‘bootstrap.php’; with the following code:
1 # 2 # BEGIN 3 # 4 # This was added to webroot/cron_scheduler.php 5 # 6 7 # Check that URI was specified and that we're called from the command line (not the web) 8 if($argc == 2 && php_sapi_name() === "cli") 9 { 10 # Set request URI 11 $_SERVER['REQUEST_URI'] = $argv[1]; 12 # Set user-agent, so we can do custom processing 13 $_SERVER['HTTP_USER_AGENT'] = 'cron'; 14 15 $Dispatcher= new Dispatcher(); 16 $Dispatcher->dispatch($argv[1]); 17 } 18 19 # 20 # END 21 # 22 # 23 #
Now you can execute CakePHP from the command line with the following command:
1 $ php cron_scheduler.php /controller/action
If you get the following error, remove the lines containing line feeds in bootstrap.php:
1 Warning: Cannot modify header information - headers already sent by (output started at .../app/config/b 2 ootstrap.php:48) in .../app/app_controller.php on line 46
How to add logging to CakePHP applications
Note that Pear’s Logging package is a lot more flexible, so I recommend you use that instead of CakePHP’s built-in logging.
Use this code to add a debug message to the CakePHP debug log:
1 $this->log("Upload action accessed", LOG_DEBUG);
Note that using something other than LOG _DEBUG will log the message as an error.
Run the code once and you should be able to see the message in $CAKE_APP/tmp/logs/debug.log.