Tutorial on How to Write to a File in PHP

Posted in Tutorials

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

In this tutorial, we will show you how to write to a log file in PHP.  Here is a basic function we called “writelog” which takes a $msg message string to be written into a log file called “log.txt” in the same directory as this PHP file…

write to log file

write to log file

You could put a full server path to log.txt instead.

1. The idea is to call fopen on this file passing it a file mode of “a” to “append”.  See other possible modes here. It will create the file if it does not exist.  And will append if it does exist.

fopen returns a file handle (which we call $handle).

If fopen can not open the file (due likely to file permission issues), then it will return false.  We use this to display error message if necessary.

2.  Then use fwrite() to actually write some text to the file.  We pass it the file handle and the text to be written.  We just prepend the message with a formatted timestamp here.

3. After writing, close file handle with fclose()

4.  You see we did a test at the end by calling writelog with one and two messages by calling this writelog function.