刷新后如何保存写入txt文件的数据



目前,我将这个PHP拼凑在一起,根据提交时是否检查输入,将0或1写入文本文件。当我在页面上提交表单时,它工作正常,但是一旦我导航到另一个页面并返回文本文件,它就会被 0 覆盖,并且不会保存写入文件的最后一个数字(无论是 0 还是 1(。

.PHP:

<?php
$file    = 'file.txt';
$current = file_get_contents($file);
if (isset($_POST['mycheckbox'])) {
  $current = "1";
} else {
  $current = "0";
}
file_put_contents($file, $current);
$alerttext = 'alert!';
if ($current == 1) {
  print $alerttext;
  $switch = 'checked';
} else {
  $switch = '';
}
?>

.HTML

<form action="#" method="post">
    <label class="switch db">
        <input type="checkbox" id="checkBox" class="switch db" 
               name="mycheckbox" value="Yes" <?php print $switch;?> 
               autocomplete="off"/>
    </label>
    <input type="submit" name="submit" value="Submit"/>
</form>

PHP:

<?php
$file    = 'file.txt';
$current = file_get_contents($file);
if ( isset( $_POST[ 'form_was_submitted' ] ) ) {
$current = ( !empty( $_POST[ 'mycheckbox' ] ) ? "1" : "0" );
file_put_contents( $file, $current );
}
if ( $current == 1 ) {
$switch = 'checked';
} else {
    $switch = '';
}
?>

.HTML

<form action="#" method="post">
    <input type="hidden" name="form_was_submitted" value="1">
    <label class="switch db"><input type="checkbox" id="checkBox" class="switch db" name="mycheckbox" value="Yes" <?php print $switch;?> autocomplete="off"/><i></i></label>
    <input type="submit" name="submit" value="Submit"/>
</form>

最新更新