我正在尝试让我的项目记住用户是否按下了复选框,如果他们返回我的网站。
在html表单上,我有以下复选框(将在onchange上重新加载页面)
<input type="checkbox" name="showcabin" <?php echo $_COOKIE['selectedcabin']?> onchange="document.getElementById('maininput').submit()" >
<label for="checkbox">Show Cabin</label>
当用户第一次运行页面
时,会运行以下php<?php
print_r ($_COOKIE); //using this to see what result is stored on page load - always blank(apart from session ID)
//check to see if check box was selected prior to page reload
if (isset($_POST['showcabin'])){
$selectedcabin = 'checked="checked"';
//If checkbox wasn't ticked when page loaded, is there a stored variable in a cookie
}elseif ($_COOKIE['selectedcabin'] == 'checked="checked"'){
$selectedcabin = 'checked="checked"';
}else{
//if not then leave variable blank
$selectedcabin ='';
}
$_COOKIE["selectedcabin"] = $selectedcabin;
echo $_COOKIE["selectedcabin"];
?>
关闭浏览器并重新打开后,我无法获取变量$ selectedcabin来保留信息。
我知道有很多方法可以使用Javascript,但是我的javascript知识非常有限,所以我不想在可能的情况下沿着这条路走下去
谢谢!
答案 0 :(得分:1)
您没有正确设置Cookie。使用类似这样的东西
<?php
$cookie_name = "showcabin";
$cookie_value = "checked='checked'";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // The cookie will expire in 86400s = 1 day
?>
设置Cookie