Search code examples
phpfopenfwritefclose

Using php to write to a log file


First of I am very very very very bad with php so sorry for this question I have an application in which i would like to log some debug data and through my project i make a webrequest to my site storing the information in $msg i then want to write the data to my logfile.log on the site. i first used fopen fwrite fclose, but heard that file_put_contents would be better especially as i very likely will have several users trying to write to the file at once. Here's the code:

$msg = $_GET['w'];
$logfile= 'logfile.log';
echo file_put_contents($logfile,$msg, FILE_APPEND | LOCK_EX);

But as you might guess the code does nothing for me i got it working with fopen fwrite fclose but i wanted to add each user to a new line.

If any smart brain out there would help me I would appreciate it a ton.

Regards.

EDIT: @Jay This is how i tried applying it (opening php on the first line) EDIT: removed 'tag' from code due to a copy/paste error.

error_reporting(E_ALL); ini_set('display_errors', 1)
$msg = $_GET['w'];
$logfile= 'logfile.log';
echo file_put_contents($logfile,$msg, FILE_APPEND | LOCK_EX);

Solution

  • Why not just use error_log()? With the message_type set to 3 (second parameter) the message will be written the the file specified in the third parameter:

    $message = $_GET['w'];
    $logfile = 'logfile.log';
    
    // Debug: A line for verifying I have the message
    echo "Writing message '$message' to logfile<br>";
    
    error_log($message."\n", 3, $logfile);
    
    // Debug: read back the log file to verify thatthe line has been written
    readfile($logfile);
    

    Note the newline appended to the message as error_log() doesn't do this for you.

    Note also that permissions must be set to allow the web server to write to the target file. This is true whether using error_log() or file_put_contents()

    PHP reference is here