i try to add two cookies in php file…but when i excute one the other is deleted
here is the code:
<?php
if (isset($_COOKIE["background"])) {
echo "<style> body { background-color:". $_COOKIE["background"] . "}</style>";
}
if (isset($_COOKIE["username"])) {
echo "<h1> " . $_COOKIE["username"] . "</h1>";
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
setcookie("username",$_POST["username"],strtotime("+1 day"));
setcookie("background", $_POST["bg-color"] , strtotime("+1 year"));
header("location: " . $_SERVER["REQUEST_URI"] ,false);
exit();
}
?>
2
Answers
I have shared just an working example. Please run this code and let me know if any issue found
You said "when i execute one the other is deleted", so I assume that sometimes you will submit the username, and sometimes you will submit the bg-color
If you only rely on the request_method to execute the statements inside the if block, both the cookie variables will be re-assigned to the submitted post variables, so you should use further isset to determine which one to perform the assignment.
Hence, please change to: