0

I have this HTML code:

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

Also I have this PHP code:

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();

As you can see, I have got all checked checkboxes and stored it to the php cookie. Now, when someone is logging to the system, all checkboxes is checked by default. But I need them to be checked or unchecked based on the info from php cookie! I mean, for example, if user logged on to the system and unchecked some checkboxes, logged off, then logged in again, previously unchecked checkboxes must remains unchecked. Please, give me some advices for doing it.

Gerhart
  • 75
  • 1
  • 2
  • 9
  • `based on the info from php session!` - don't get cookies and sessions mixed up. Also.. use sessions, cookies have a lot of cons (see here: https://stackoverflow.com/questions/6253633/cookies-vs-sessions) and if you're using session you can do something like this to achieve you're goal: `` – treyBake Jun 11 '18 at 11:47
  • Sorry, I've mistaken. Yes, I've meant cookies, no sessions. – Gerhart Jun 11 '18 at 11:50
  • my statement stands that you should switch to sessions, they're 100X better and easier to use .. – treyBake Jun 11 '18 at 11:50
  • Yes, I understand. You're right. But what if user wants to see unchecked checboxes after he'll close his browser and open it again? – Gerhart Jun 11 '18 at 11:52
  • store it in a db table, nothing is worth cookies imo – treyBake Jun 11 '18 at 11:53

1 Answers1

1

Put your cookie in an array say

$cookie_aray=check_cookies();

and check it every time you load a check box, whether it was selected or not.

<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">

Penguine
  • 519
  • 6
  • 19