2014-02-24 94 views
-2
<?php 
if (isset($_POST['1'])) { 
    $file = 'count.txt'; 
    $current_count = file_get_contents('count.txt'); 
    file_put_contents($file,str_replace($current_count,$current_count + 1,file_get_contents($file))); 
    $handle = fopen('count.txt', 'w'); 
    fwrite($current_count, $handle); 
    fclose($handle); 
} 
?> 

我想做一个简单的计数器。当我按下一个按钮时,它会把我带到这个php文件中,并带有该代码。该代码应该读取count.txt中的内容,数字“1”,并将其替换为2,即1加1。出于某种原因,这是行不通的。我可能做错了什么。请帮助我发现我的错误或另一种方式来做到这一点。我需要重申一个按钮直接链接到这个PHP脚本,所以我可能不需要$ _POST。为什么这个PHP不工作?

+0

使用file_put_contents OR FWRITE,而不是两个,目前后者将覆盖前者 – 2014-02-24 01:08:01

+0

@Dagon它仍然心不是工作。我删除了最后三行,从“$ handle”开始。 – user2985562

+1

它以什么方式“不工作”? – 2014-02-24 01:10:22

回答

0

这是测试和工程

<?php 

if (isset($_POST['1'])) { 
    $file = 'count.txt'; 
    $current_count = file_get_contents($file); 
    $current_count++; 
    file_put_contents($file, $current_count); 
} else { 
    die("Post Not Set"); 

}

0

这是因为你是如何做。简而言之,您将从文件中获取计数,将其存储在$ current_count中,使用增加的计数写入文件,对文件进行破坏,最后将原始计数写回文件。

if (isset($_POST['1'])) { 
    $file = 'count.txt'; 
    // At this point, $current_count will be 1 
    $current_count = file_get_contents('count.txt'); 

    // $current_count will still be 1 after this line. 
    // It is not incremented. The file will have a 2 
    // in it though as you are writing what $current_count + would be. 
    file_put_contents($file,str_replace($current_count,$current_count + 1,file_get_contents($file))); 

    // File gets clobbered(emptied) by opening it with a 'w'. 
    $handle = fopen('count.txt', 'w'); 

    // You then write a 1 right back to the file, because 
    // that is what $current_count is equal to. 
    fwrite($current_count, $handle); 
    fclose($handle); 
} 

,你需要的至少是这样的:

<?php 
    $file = 'count.txt'; 

    $current_count = file_get_contents('count.txt'); 
    file_put_contents($file,str_replace($current_count,$current_count + 1,file_get_contents($file))); 
?> 
+0

抱歉是一个**,但它没有两个。我想知道如果我可以拿出$ _POST,如果你不明白为什么,请重读原始问题。如果它不能被删除,它应该保留为['1']的值是什么? – user2985562

+0

真的...重新读你的问题。重新阅读我的答案。您在原始代码中两次写入文件 - 一次是增加值,一次是原始值。 – Buggabill

+0

我说因为我编辑了这个问题。我完全理解你的答案,它非常有用,但它仍然不起作用(count.txt是相同的)。我不知道为什么。 – user2985562