Home > database >  How can I excute two cookies in same time with php
How can I excute two cookies in same time with php

Time:12-02

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

CodePudding user response:

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

CodePudding user response:

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();
}
  •  Tags:  
  • php
  • Related