Home » Php » logging – running a php script via cron, how can I log any output?

logging – running a php script via cron, how can I log any output?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Morning all,

I have a php script which I have been testing, and seems to run fine when I call it from the command line.

I now want to automate it via cron, how can I get the outputs I have put into the file as checkpoints into a log file?

eg I have some simple echo commands in the script and I’d like the output to appear inside an existing log file (so that it get’s automatically rotated etc)

thanks,

Greg

How to&Answers:

Cron command to run:

/path/to/php -f /path/to/script.php >> /path/to/logfile.txt

Answer:

Try something like this:

<?php
function logToFile($filename, $msg)
{ 
    $fd = fopen($filename, "a");
    $str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
    fwrite($fd, $str . "\n");
    fclose($fd);
}

function logToMail($msg, $address)
{ 
    $str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;   
    mail($address, "Log message", $str);
}

function logToDB($msg, $type)
{ 
    // open connection to database
    $connection = mysql_connect("localhost", "joe", "pass") or die ("Unable to connect!");
    mysql_select_db("logdb") or die ("Unable to select database!");

    // formulate and execute query
    $query = "INSERT INTO log (date, type, msg) VALUES(NOW(), '$type', '$msg')";
    mysql_query($query) or die ("Error in query: $query. " .mysql_error());

    // close connection
    mysql_close($connection);
}
?>