dimanche 10 septembre 2017

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!

Aucun commentaire:

Enregistrer un commentaire