使用php

时间:2018-10-30 00:29:38

标签: php file checkbox persistent

我正在尝试将复选框的状态(是真还是假(选中/未选中))保存到文件中。我设法将checkbox值写入文件,但是我不知道这是否是正确的方法,而且我也不知道如何再次加载它。 我希望通过重新加载页面来“记住”上次的复选框状态。 可悲的是,使用本地存储对我来说不是一种选择。.

这是我的代码:

<form action="database.php" method="post">
<input type="hidden" name="check2" value="0" /> 
<input type="checkbox" name="check2" value="1" /> 

<input type="submit"  value="senden" />
</form>



<?php

$handle = fopen("saver.json", "a");

$fh = fopen( 'saver.json', 'w' );
fclose($fh);  
  
 foreach($_POST as $value) {
  fwrite ($handle, $value);

 }
 
 fclose($handle);

?>

因此,这首先删除了旧的保存的值,然后在文件中写入1或0。 我是在做一个好方法还是我觉得太简单了?

高度赞赏所有帮助! 非常感谢

1 个答案:

答案 0 :(得分:1)

尝试此解决方案,提交,重新加载甚至重新启动浏览器后,所有复选框状态都会保留:

<?php
// Use SESSION to store checkbox status data. SESSION seems to have a lifetime, that will erase itself if exceed.
// If you need preserve status after browser closed (), you might need to consider storing them into a file.
session_start();

$sessionTgt = NULL;

// You probaby won't need this, but if you have corrupted session
// , use "localhost://my/url/thisScript.php?reset=1" to reset/erase this session key ("saveCheckBox").
if ($_SERVER["REQUEST_METHOD"] === "GET" && isset($_GET["reset"]) && $_GET["reset"] === "1" ) {
    unset($_SESSION["saveCheckBox"]);
    echo("Ok, have just reset \$_SESSION[\"saveCheckBox\"]:");
    exit();
}

// Reset this session key ("saveCheckBox") if it was not set.
if (!isset($_SESSION["saveCheckBox"])) {
    $_SESSION["saveCheckBox"] = [
        // "0" means server tell client no redirect. "1" means redirect immediately.
        "ifRedirect" => "0",
        // Store checkbox checked status. Example data will look like this:
        // [
        //     "ckBox1" => "checked",
        //     "ckBox4" => "checked"
        // ]
        // , it means checkbox "ckBox1" and "ckBox4" are checked, others are not.
        "checkBoxData" => [],
    ];
}

// Passing "reference", not value, to variable $sessionTgt.
$sessionTgt = &$_SESSION["saveCheckBox"];

// Print html form, by some condition. if some of the checkbox have "checked" status
// , then append the string "checked" inside their html <input> tag
// , so the input box will displayed as "checked".
function printFormAndCheckStatus ($checkStatus = NULL) {
    echo(
        '<form action="" method="post">' .
        '<input type="checkbox" name="ckBox1" value="checked" ' . printCheckedMaybe("ckBox1", $checkStatus) . ' />' .
        '<input type="checkbox" name="ckBox2" value="checked" ' . printCheckedMaybe("ckBox2", $checkStatus) . ' />' .
        '<input type="checkbox" name="ckBox3" value="checked" ' . printCheckedMaybe("ckBox3", $checkStatus) . ' />' .
        '<input type="checkbox" name="ckBox4" value="checked" ' . printCheckedMaybe("ckBox4", $checkStatus) . ' />' .

        '<input type="submit"  value="Submit" />' .
        '</form>'
    );
}

function printCheckedMaybe ($nameAttribute, $checkStatus) {
    if (isset($checkStatus[$nameAttribute])) {
        return "checked";
    } else {
        return "";
    }
}

// POST "bouncing" logic. Notice the sequence is like this:
// -> Client get new page (client)
// -> Client user checked checkbox and post (client)
// -> Server save post data to SESSION (server)
// -> Server ask client for redirect (server)
// -> Client redirect immediately without doing anything (client)
// -> Server give back modified form content, that some input box has "checked" string
// appended inside the tag (client).
// The reason using double request instead of one, is to PREVENT POST DATA GET POSTED TWICE, which confuse server.
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $sessionTgt["ifRedirect"] = "1";
    $sessionTgt["checkBoxData"] = [];
    if (isset($_POST)) {
        foreach ($_POST as $name => $value) {
            $sessionTgt["checkBoxData"][$name] = $value;
        }
    }
    header("Refresh:0");
    // When client get this response header pattern/content, client (browser) know he need to
    // refresh the page immediately (request the same url again).
} else {
    if ($sessionTgt["ifRedirect"] !== "1") {
        if (isset($sessionTgt["checkBoxData"])) {
            printFormAndCheckStatus($sessionTgt["checkBoxData"]);
        } else {
            printFormAndCheckStatus();
        }
    } else {
        // Just after redirect.
        $sessionTgt["ifRedirect"] = "0";
        printFormAndCheckStatus($sessionTgt["checkBoxData"]);
    }
}

这可以解决您的问题吗?此解决方案将您的复选框状态保存在服务器SESSION中,但是SESSION似乎有生存期,如果超过该生存期,则将自身清除。 (也许我错了)。如果需要长期存储,可以将其写入文件或数据库。