使用PHP覆盖文件问题

I have to write a file, in order to increase a value, but sometimes (when the file is opened two times in a row) it increases only by one instead of two.

This is part of the script executed two times in a row:

include "changevar.php";//declare the changevar function
include $file;//get user's impressions
changevar("impressions",$impressions+1,$file,1);//increase the impressions by 1

And this is the changevar.php file:

<?
function changevar($varname,$newval,$filename,$type)
{
    while(!$fp=fopen($filename,"c+"))
    {
        usleep(100000);
    }
    while(!flock($fp,LOCK_EX))
    {
        usleep(100000);
    }
    $contents=fread($fp,filesize($filename));
    ftruncate($fp,0);
    rewind($fp);
    eval(substr(substr($contents,2),0,-2));
    $$varname=$newval;
    if($type==0)//avoid reading this, in this case $type equals to 1
    {
        $u=str_replace("\"","\\\"",$u);
        $p=str_replace("\"","\\\"",$p);
        $t=str_replace("\"","\\\"",$t);
        $d=str_replace("\"","\\\"",$d);
        $text="<?\$o=$o;\$u=\"$u\";\$c=$c;\$m=$m;\$p=\"$p\";\$C=$C;\$id=\"$id\";\$t=\"$t\";\$d=\"$d\";\$O=$O;?>";
    }
    else//true, $type equals to 1
    {
        $text="<?\$impressions=$impressions;\$clickunici=$clickunici;\$clicknulli=$clicknulli;\$creditiguadagnati=$creditiguadagnati;\$creditiacquistati=$creditiacquistati;\$creditiutilizzati=$creditiutilizzati;?>";
    }
    fwrite($fp,$text);
    fflush($fp);
    flock($fp,LOCK_UN);
    fclose($fp);
}
?>

As I just said, the script works fine, except if it is executed two times in a row.

I think that the problem is in $contents=fread($fp,filesize($filename));, because it reads the files before it is written.

I already used the flock function, but it doesn't solve this problem.

So, how can I fix the code?

It's not clear what you're doing since you only give bits and pieces of your code, and you don't show the content of the file read; but if you want to increment the value in the file, you should be adding one to a number you read from the locked file-- not writing an argument ($impressions+1) that you pass to changevar() from the outside. Rethink the logic of your code and fix it.