简体   繁体   中英

Cookie not being saved when checkbox is clicked

I have a checkbox that when I click I want it to set a cookie with a value of an array. But when I click on the checkbox it doesn't set my cookie.

I don't understand why it is not being set. Is there something wrong with how I am creating the array for the value of the cookie?

Here is my code:

 extract($_POST);
 $code = $_POST['code'];
 $total= 100;
 if(isset($save)){
        echo "Saved";
        $cookie = array(
            'name'   => $code,
            'value'  => $total,
    );
    setcookie("cookie",json_encode($cookie),86500);
}

 if(isset($_COOKIE['cookie'])){
        echo "SET";
    }else{
        echo "NOT SET";
    }


<form method='post'>
     <input type="checkbox" name="save" value="1">Save
     <input name='code' />
</form
  1. As mentioned by CBroe, you should avoid using extract (for security).

  2. You should have a submit button (but I suppose you have one but did not include in your code posted, right?)

  3. Please use a time() to calculate the life span of the cookie, so use something like:

setcookie("cookie",json_encode($cookie),time()+3600);
  1. use a header redirection to reload your script upon setting cookies (as follows) - so as to show the latest status of the cookie:
header('Location: '.$_SERVER['PHP_SELF']);

Hence, Please use the following code:

<?php
// extract($_POST);
 $code = $_POST['code'];
 $total= $_POST['total'];
 if( isset($_POST["save"]) ){

    if ($_POST["save"]=="1") {
        echo "Saved";
        $cookie = array(
            'name'   => $code,
            'value'  => $total,
    );
    setcookie("cookie",json_encode($cookie),time()+3600);
}
header('Location: '.$_SERVER['PHP_SELF']);
die;
}

 if(isset($_COOKIE['cookie'])){
        echo "SET";

$getcookie=json_decode($_COOKIE['cookie']);
echo "<br>Name:". $getcookie ->name;
echo "<br>Value:". $getcookie ->value;
echo "<br>";

    }else{
        echo "NOT SET";
    }

?>

<form method='post' action=#>
     <input type="checkbox" name="save" value="1">Save (must tick to save as cookie)
     <input name='code' placeholder='Enter Name'/>
     <input name='total' placeholder='Enter a value'/>

     <input type=submit>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM