tags:

views:

40

answers:

3

From my age old php days (years ago) I slightly remember that I had big trouble with creating a log file in PHP. At random times, the file suddenly was plain blank (empty). I used something pretty close to this:

$myFile = "myFile.txt";
$fh = fopen($myFile, 'a');
$str = "New Entry...\n";
fwrite($fh, $str);
fclose($fh);

Is that really a safe way to work with a error log file when there are like 500 users at the same time executing PHP scripts (by surfing the website)? Lets assume there's a really bad bug that causes every page view to produce an error log. That poor myFile.txt is then accessed like 100 times per second. I feel that this won't work. I hope I'm wrong.

How would you do that?

A: 

Depending upon your filesystem, you may have race conditions that result in lost log entries, but the total contents should never disappear.

If you want dependable logs, then you will have to write-lock the file before writing your entry.

Alternatively, put the entries in a database.

Frank Krueger
+1  A: 

http://de.php.net/manual/en/function.file-put-contents.php with FILE_APPEND and LOCK_EX Alternatively http://de.php.net/manual/en/function.error-log.php

Gordon
with file_put_contents, appends are atomic, so there is no need for LOCK_EX, if you are using FILE_APPEND
Pascal MARTIN
Thanks Pascal. Another reason to RTFM first before asking here. Human memory is so volatile :)
Gordon
You're welcome :-) (Actually, though, I would have removed the LOCK_EX part, and kept the FILE_APPEND one ^^ ) -- and about the RTFM : a couple of month ago, the fact that those are mutually exclusive was not specified in the manual (I remember a question about that on SO ^^ )
Pascal MARTIN
+1 ; Thanks for the edits ;-)
Pascal MARTIN
A: 

Use flock.

But also (!) note:

"File locking requires a fairly modern file system, such as NTFS (Windows), ext3/ext4 (Linux) and HFS+ (Mac). Furthermore, the Network File System (NFS), commonly used to provide file sharing across Unix boxes, is not suitable for use with flock(). " http://tuxradar.com/practicalphp/8/11/0

"On many platforms (including most versions or clones of Unix), locks established by flock() are merely advisory. Such discretionary locks are more flexible, but offer fewer guarantees. This means that files locked with flock() may be modified by programs that do not also use flock(). Windows NT and OS/2 are among the platforms which enforce mandatory locking. See your local documentation for details." http://www.sdsc.edu/~moreland/courses/IntroPerl/docs/manual/pod/perlfunc/flock.html

Maybe some other program (or process?) is cleaning out your file...?

I also seem to remember that some article I read said that not only is using flock on files in Windows or SMB network shares not recommended but that it is buggy.

martinr