skip to Main Content

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


  1. <?php 
        $row = array(
            'User_Id' => '10',
            'username' => 'Rohan',
            'bg-color' => 'Red',
            'Db_Sys' => '1'
        );
    
        setcookie("username",$row["username"],strtotime("+1 day"));
        setcookie("background", $row["bg-color"] , strtotime("+1 year"));
    ?>
    

    I have shared just an working example. Please run this code and let me know if any issue found

    Login or Signup to reply.
  2. 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:

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
      if (isset($_POST["username"]))  {
        setcookie("username",$_POST["username"],strtotime("+1 day"));
      }
    
      if (isset($_POST["bg-color"]))  {
        setcookie("background", $_POST["bg-color"] , strtotime("+1 year"));
      }
    
        header("location: " . $_SERVER["REQUEST_URI"] ,false);
        exit();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search