目前我将这个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>
答案 0 :(得分:0)
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>