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
CodePudding user response:
As mentioned by CBroe, you should avoid using extract (for security).
You should have a submit button (but I suppose you have one but did not include in your code posted, right?)
Please use a time() to calculate the life span of the cookie, so use something like:
setcookie("cookie",json_encode($cookie),time() 3600);
- 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>