cakephp snippets

How to add logging to CakePHP applications

Tagged cakephp, php, debug, logging  Languages php

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:

$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.

How to execute a CakePHP controller's action from a cron job

Tagged job, cakephp, cron  Languages php

First copy webroot/index.php to webroot/cron_scheduler.php. Replace everything below require CORE_PATH . 'cake' . DS . 'bootstrap.php'; with the following code:

# This was added to webroot/cron_scheduler.php

# Check that URI was specified and that we're called from the command line (not the web)
if($argc == 2 && php_sapi_name() === "cli") 
    # Set request URI
    $_SERVER['REQUEST_URI'] = $argv[1];
    # Set user-agent, so we can do custom processing
    $_SERVER['HTTP_USER_AGENT'] = 'cron';
    $Dispatcher= new Dispatcher();


Now you can execute CakePHP from the command line with the following command:

$ php cron_scheduler.php /controller/action

If you get the following error, remove the lines containing line feeds in bootstrap.php:

Warning: Cannot modify header information - headers already sent by (output started at .../app/config/b
ootstrap.php:48) in .../app/app_controller.php on line 46