Nikos Nikos - 2 days ago 4
PHP Question

fwrite saves same message multiple times

I use fwrite in php to log some errors in logs.txt.

The problem is that when I open db_errors.txt I see the message saved multiple times instead of just once.

My fwrite code is not inside any loop, so it is definately executed only once. Same think happended using third party logger classes.

if (!$result = mysqli_query($link, $query)){
$today = getdate();
$handle = fopen("logs/db_errors.txt", "a");
fwrite($handle, $today['mday'].'/'.$today['mon'].'/'.$today['year']." | ".mysqli_errno($link)." : ".mysqli_error($link)." | ".$query." \n");
fclose($handle);
}


this writes in 3 lines inside db_errors.txt with the same output.

11/4/2011 | 1054 : Unknown column 'uids' in 'field list' | SELECT uids FROM users WHERE user_id=6 LIMIT 1
11/4/2011 | 1054 : Unknown column 'uids' in 'field list' | SELECT uids FROM users WHERE user_id=6 LIMIT 1
11/4/2011 | 1054 : Unknown column 'uids' in 'field list' | SELECT uids FROM users WHERE user_id=6 LIMIT 1

Answer

My fwrite code is not inside any loop, so it is definately executed only once. Same think happended using third party logger classes.

If someone else's code shows the same behavior, then you have only one possible root cause: The code is being called three times.

It's probably time to get out a debugger and add a breakpoint to your code, then step through everything that happens after the first call. This will undoubtedly lead you to the source of the later calls.

You might also want to consider adding a full timestamp and a microtime to the log instead of getdate. This may make troubleshooting more effective by proving that there are indeed three calls being made.

$time_plus_micro = date('Y-m-d H:i:s') . ' ' . microtime(true)
fwrite($handle, $time_plus_micro . " | ...";
Comments