开发者

PHP problems with writing to files

If I create a counter program that basically loads the text file "counter.txt" and then it reads the file and if it contains a number it increments the number by 1 and the updates the file with the number and saves the file.

The code for the above program works fine for lets say 1 execution per second, but the problem starts when the execution times go very high such as 100 per second.

The problem I face is that the file content is sometimes erased and sometimes the counter is not counting properly. So lets say I run 100 executions per second but the count will only go up by 10. I am definitely sure that all the executions are completed because each execution writes a file after incrementing the number and there are 100 files written in another directory for the number of executions but the count in the is only increme开发者_如何学Cnted by 10.

    <?php 
$File = "counter.txt"; 
$handle = fopen($File, 'r+') ;
$data = fread($handle, 512) ; 
 $count = $data + 1; 
fseek($handle, 0) ; 
 fwrite($handle, $count) ; 
 fclose($handle) ; 
 ?> 


The problem is that two files count at the same time. The counter will not be set properly. You need to make sure; the file is only accessed once at a time.

Process1: Reads File and gets 0 
Process1: Increments 0 to 1 
Process2:Reads File and gets 0 
Process1: Writes 1 to File 
Process2: Increments 0 to 1 
Process2: Write 1 to File


Hi @MasterCassim is Right.

Use flock ( http://php.net/manual/en/function.flock.php ) to lock the file

<?php
//some code here
flock($file_handle, LOCK_EX) // <- Your code will pause here until you get the lock for indefinite amount of time or till your script times out
//some code here
?>


If you by chance already use a DB with your php-pages, you could put the counter into it, then you would have a mere UPDATE statement with SET counter = counter + 1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜