为什么这个php不工作?

为什么这个php不工作?,php,html,file,add,Php,Html,File,Add,我想做一个简单的计数器。当我按下一个按钮时,它会将我带到这个php文件,其中包含该代码。代码应该读取count.txt中的数字“1”,并将其替换为2,即1加1。出于某种原因,这是行不通的。我可能做错了什么。请帮我发现我的错误或另一种方法。我需要重申一点,一个按钮直接链接到这个php脚本,所以我可能不需要$\u POST。这是经过测试的,可以正常工作 <?php if ( isset( $_POST['1'] ) ) { $file = 'count.txt'; $curre

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

这是经过测试的,可以正常工作

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

这是因为你是如何做到这一点的。简而言之,您将从文件中获取计数,将其存储在$current_count中,使用递增的计数写入文件,删除文件,最后将原始计数写回文件

<?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");
您至少需要这样做:

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


使用file\u put\u contents或fwrite,而不是两者,当前后者将覆盖former@Dagon它仍然不起作用。我删除了从“$handle”开始的最后三行。它以什么方式“不工作”?@Dagon它没有给出预期的结果。我仍然拥有count.txt中的数字1。您是否检查了该文件的权限?很抱歉是a**,但其中没有2。我想知道,如果你不明白为什么,我是否可以拿出$_的帖子,重读原来的问题。如果它不能被删除,post值应该是什么,它应该保持为['1']?真的。。。重读你的问题。重读我的答案。您在原始代码中编写了两次文件-一次使用递增值,一次使用原始值。我之所以这么说是因为我编辑了问题。我完全理解你的答案,这是非常有用的,但它仍然不起作用(count.txt是相同的)。我不知道为什么。
 <?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)));
 ?>