Php “写入文本文件”将无法与单击的第一项一起使用

Php “写入文本文件”将无法与单击的第一项一起使用,php,text,fopen,file-get-contents,file-put-contents,Php,Text,Fopen,File Get Contents,File Put Contents,我有一个奇怪的问题,我不知道怎么了。我正在编写一张美国的交互式地图。用户单击一个状态,单击将记录在文本文件中。然后点击总数显示在地图上。它基本上是一个围绕完整数据库的快速解决方案 代码是有效的。每次单击某个状态时,它都会添加到文本文件中。如果该状态尚不存在,则会为其创建一个条目。如果是这样,那么点击次数只需更新即可。文件如下: <?php // get the input from AJAX @$state = $_GET['state']; // get the

我有一个奇怪的问题,我不知道怎么了。我正在编写一张美国的交互式地图。用户单击一个状态,单击将记录在文本文件中。然后点击总数显示在地图上。它基本上是一个围绕完整数据库的快速解决方案

代码是有效的。每次单击某个状态时,它都会添加到文本文件中。如果该状态尚不存在,则会为其创建一个条目。如果是这样,那么点击次数只需更新即可。文件如下:

<?php 
    // get the input from AJAX
    @$state = $_GET['state'];
    // get the txt file where all of the states are 
    $file = 'state_count.txt';
        //if state_count.txt exists 
        if($fopen = fopen($file, 'c')){ 
            //open it and check if the name of the state is recorded or not 
            if($strpos= strpos(file_get_contents($file), $state)){
                //if so, add 1 to the value after the state's name
                // in the formate State:#
                //cut the text file into an array by lines 
                $lines = file($file);
                //foreach line, parse the text 
                foreach($lines as $l => $k){ 
                    // create a new array $strings where each key is the STATE NAME and each value is the # of clicks 
                    $strings[explode(':', $k)[0]] = explode(':', $k)[1];
                } 
                // add 1 to the # of clicks for the state that was clicked
                $strings[$state] = $strings[$state]+1;  
                // move cursor to the end of the state's name and add 1 to accomodate the : 
                fseek($fopen, $strpos+strlen($state)+1, SEEK_SET); 
                // overwrite number in file
                fwrite($fopen, $strings[$state]); 

                // debug print($strings[$state]);

            }
            //if not, add it with the value 1
            else{ 
                file_put_contents($file, $state.":1\n", FILE_APPEND); 
            } 
        }   
        //if does not exist
        else{ 
            die('Cannot create or open file.'); 
        } 

?>
我不知道它为什么要这样做,所以我希望一双新鲜的眼睛能指出一些明显的东西。。。我觉得这与
if($strpos=strpos(file\u get\u contents($file),$state))中的line if语句有关{
,但我不能确定。除了您单击的第一个状态外,代码对所有内容都100%正确运行似乎是一个奇怪的问题。我知道这是第一个状态,只是因为我尝试过多次,将不同的状态作为第一个状态


有什么想法或建议吗?

请注意,当您使用strpos查看字符串是否存在时,应检查布尔值:

if (strpos(....) !== false) { ... }
否则,当STRPO返回0时,您将出现假阴性,就像您的情况一样

在您的代码中,您可以采用如下方法:

$strpos= strpos(file_get_contents($file), $state);
if ($strpos !== false) {...

今天为数不多的几个格式正确的问题之一。您检查是否可以成功设置$strpos的值…;)是否想过这可能是一个字母大小写问题?请尝试
stripos
如果是这种情况,这是不区分大小写的问题。@Bioshade不要害羞地叫我出来;我不会感到生气;-)我将删除注释,直到您这样做。就目前而言,您的评论是针对OP的。在这种情况下,我不认为
stripos
有任何作用,因为除了一个独特的情况外,代码适用于所有情况(因此对于其他条目来说,区分大小写不是问题)。bksi下面的回答是实际问题。
$strpos= strpos(file_get_contents($file), $state);
if ($strpos !== false) {...