Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP覆盖文件问题_Php_File_Overwrite - Fatal编程技术网

使用PHP覆盖文件问题

使用PHP覆盖文件问题,php,file,overwrite,Php,File,Overwrite,为了增加一个值,我必须编写一个文件,但有时(当文件连续打开两次时),它只增加一个而不是两个 这是连续执行两次的脚本的一部分: include "changevar.php";//declare the changevar function include $file;//get user's impressions changevar("impressions",$impressions+1,$file,1);//increase the impressions by 1 这是changeva

为了增加一个值,我必须编写一个文件,但有时(当文件连续打开两次时),它只增加一个而不是两个

这是连续执行两次的脚本的一部分:

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

<?
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);
}
?>

正如我刚才所说,脚本运行良好,除非它连续执行两次

我认为问题在于
$contents=fread($fp,filesize($filename)),因为它在写入文件之前读取文件

我已经使用了
flock
函数,但它没有解决这个问题


那么,如何修复代码呢?

不清楚您在做什么,因为您只给出代码的一部分,而不显示读取的文件内容;但是,如果要增加文件中的值,则应将一个值添加到从锁定文件读取的数字中,而不是写入从外部传递给
changevar()
的参数(
$impressions+1
)。重新思考代码的逻辑并修复它

您可以在
sys\u get\u temp\u dir()
中创建互斥体,并在最后将其删除。如果它已经存在,请随机等待。为什么会有这样一个一般性的问题?为什么不找到并修复阻止
flock()
正常工作的任何东西呢?您真的需要在一次执行中多次打开/读取/写入/关闭一个文件吗?如果将数据到文件的提交移动到脚本的末尾,即每次执行仅发生一次,并且仅在必要时发生,那么代码的稳定性、服务器上的IO负载、脚本的响应性以及您的理智性都会更好。否则,为了事务的简单性和原子性,您最好使用数据库。@Sammitch它是一个计数器,所以我想我需要这样做。。。如果你有更好的解决方案,就写在这里:)@MaximKhan Magomedov好主意,如果我不能使用flock函数,我会考虑这个问题