设置基于php cookie检查的复选框

时间:2018-06-11 11:27:42

标签: php

我有这个HTML代码:

<form action="index.php" method="post">
<input id="firstCheck" type="checkbox" name="test[]" value="first" checked>
<label for="firstCheck">1</label><br>
<input id="secondCheck" type="checkbox" name="test[]" value="second" checked>
<label for="secondCheck">2</label><br>
<input type="submit" name="test_submit" value="Send">
</form>

我也有这个PHP代码:

function create_cookies()
{
    if (isset($_POST['test_submit'])) {
        $checkboxes_array = $_POST['test'];
        setcookie("testcookie1234556", json_encode($checkboxes_array), time()+3600);
    }
}

create_cookies();

function check_cookies()
{
    if (isset($_COOKIE['testcookie1234556'])) {
        $my_cookie_array = json_decode($_COOKIE['testcookie1234556']);
        return $my_cookie_array;
    } else {
        return false;
    }
}

check_cookies();

正如您所看到的,我已经检查了所有复选框并将其存储到php cookie中。 现在,当有人登录系统时,默认情况下会选中所有复选框。但我需要根据php cookie的信息检查或取消选中它们! 我的意思是,例如,如果用户登录到系统并取消选中某些复选框,注销,然后再次登录,则必须保持未检查以前未选中的复选框。 请给我一些建议。

1 个答案:

答案 0 :(得分:0)

将你的cookie放在一个数组中

$cookie_aray=check_cookies();

并在每次加载复选框时检查它,无论它是否被选中。

<html><form action="abc.php" method="post">
<input id="firstCheck" type="checkbox" name="test[]" value="first" <?php if(in_array('first',$cookie_aray)) echo 'checked';?>>
<label for="firstCheck">1</label><br>
<input id="secondCheck" type="checkbox" name="test[]" value="second" <?php if(in_array('first',$cookie_aray)) echo 'checked';?>>
<label for="secondCheck">2</label><br>
<input type="submit" name="test_submit" value="Send">