WillMaddicott
WillMaddicott

Reputation: 532

PHP $_COOKIE to remember checkbox result

I'm trying to get my project to remember if a user has pressed a checkbox or not if they return to my site.

On an html form I have the following checkbox (will reload the page onchange)

<input type="checkbox" name="showcabin" <?php echo $_COOKIE['selectedcabin']?> onchange="document.getElementById('maininput').submit()" > 
<label for="checkbox">Show Cabin</label>

The below php is run when a user first runs the page

<?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"];

?>

I just can't get the variable $selectedcabin to retain information after I close my browser and reopen.

I'm aware there's ways to do this with Javascript, however my javascript knowledge is very very limited, so I don't want to go down this route if possible

Thanks!

Upvotes: 0

Views: 2266

Answers (1)

kator
kator

Reputation: 959

You are not setting the cookie correctly. Use something like this

<?php
$cookie_name = "showcabin";
$cookie_value = "checked='checked'";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // The cookie will expire in 86400s = 1 day
?>

To set your cookies

Upvotes: 1

Related Questions