使用php将复选框状态写入/读取文件

Posted

技术标签:

【中文标题】使用php将复选框状态写入/读取文件【英文标题】:Write and Read Checkbox status to/of file with php 【发布时间】:2018-10-30 00:29:37 【问题描述】:

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

这里是我的代码:

<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】:

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

<?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 似乎有一个生命周期,如果超过,它将自行清除。 (也许我错了)。如果您需要长期存储,可以将其写入文件或数据库。

【讨论】:

以上是关于使用php将复选框状态写入/读取文件的主要内容,如果未能解决你的问题,请参考以下文章

PHP文件写入和读取详解

PHP 文件写入和读取(必看篇)

PHP如何写入,读取与替换文件内容

如何使用 PHP 读取和写入 ini 文件

逐行读取文件

PHP:读取和写入 Excel 文件