Tutorials PHP Writing to a file

Writing to a file

Today you will learn how to use PHP to write text to another file. This is very useful if you want to keep a log file on your site.

How do I write a file?

If there is no file currently there, a new file will be created.

// location and name of the log file
$logfile = 'log.txt';

// open the log file
$log = fopen($logfile, 'w') or die('Error opening log file. Please contact system administrator');

// contents of the log file
$string = 'Log Test';

// write the log file
fwrite($log, $string);

// close the file
fclose($log);

Note: This will create a new file every time. If there is another file with the same name, it will overwrite it.

How do I keep writing to a single file?

If you want to make one continuous file, use this method. The only change from above is using a instead of w when you open the file. This will put the cursor at the end of the content before it starts writing.

$log = fopen($logfile, 'a') or die('Error opening log file. Please contact system administrator');

I don't have any moderators on this site currently, but I already have a system that logs every moderator action in the event I decide to assign someone. Santa knows if you've been naughty or nice. That's all for today. See you all next time.

Posted by on . Category: PHP


Comments

No comments posted yet

You need to register or login to post new comments.