Home » Php » crontab php file and output to log file result

crontab php file and output to log file result

Posted by: admin July 12, 2020 Leave a comment

Questions:

cron line look’s like:

*/1 * * * * /usr/bin/php /path/to/CRON.php > /path/to/log/CRON_LOG.txt 2> /dev/null

CRON.php

<?php
require_once 'config.php';
define('CRON', dirname(dirname(__FILE__)));
$parts = explode("/",__FILE__);
$ThisFile = $parts[count($parts) - 1];
chdir(substr(__FILE__,0,(strlen(__FILE__) - strlen($ThisFile))));
unset($parts);
unset($ThisFile);

$CRON_OUTPUT = "STARTING CRON @ ".date("m-d-Y H:i:s")."\r\n";
$CRON_OUTPUT .= CleanLog() . "\r\n";
$CRON_OUTPUT .= "\r\n";

echo $CRON_OUTPUT;
$fh = fopen(''.CRON.'/log/CRON_LOG.txt', 'a');
fwrite($fh, $CRON_OUTPUT);
fclose($fh);
die();
?>

CleanLog function:

    global $db;
    $resp = '';
    $db->query('SQL');  
    $resp = 'Deleted '.$db->rows_affected.' entries from table';
    return $resp;

In file only these two lines showing and function by the time as i can see executed two times:

CRON_LOG.txt

STARTING CRON @ 02-26-2012 21:26:01
Deleted 0 entries from table

STARTING CRON @ 02-26-2012 21:26:01
Deleted 0 entries from table

What’s wrong with it, why it only produce those lines and file doesn’t updated (in file only date/time changing, nothing more, it should add more lines and even file size should grow up) ?

How to&Answers:

You should be using >> for redirection to append to the file, rather than > which overwrites the log each time the script runs.

*/1 * * * * /usr/bin/php /path/to/CRON.php >> /path/to/log/CRON_LOG.txt 2> /dev/null
##---------------------------------------^^^^^^

There really isn’t any need to do fopen()/fwrite() inside the script itself, since the cron job is already handling the output redirection.