lovecoding
lovecoding

Reputation: 43

Cookies function not saving the Data

This code is intended to just take an ID and Pass without any kind of authentication and remember the data if the checkbox were to be checked. I can not figure it why is it not saving the data to cookies.

<?php

if(isset($_POST["chk"],$_POST["id"],$_POST["pass"])) {

   $id=$_POST["id"];
   $pwd=$_POST["pass"];

     if (isset($_POST["chkbx"])){

      setcookie("id","$id",time()+3600);        
      setcookie("pwd","$pwd",time()+3600);
         $id=$_COOKIE["id"];
         $pwd=$_COOKIE["pwd"];
  }
  print "Your ID " . $id;
  print "Your PASS ". $pwd;
  }
  ?>
 <html>
<head>
    <title>
        Remember Me
    </title>
</head>
<body>
    Please Enter ID and PASS
    <form method="post" >
       Enter ID
        <input type="text" name="id" />
       Enter PASS
        <input type="text" name="pass" />
   <input type="submit" value="submit" /><br>
   <input type="checkbox" name="chkbx" />Remember Me
   <input type="hidden" name="chk" value="true" />
    </form>
</body>
</html>

Upvotes: 1

Views: 37

Answers (1)

Joseph
Joseph

Reputation: 6259

You code is correct but it needs to clean it up

in this part I add a condition to check is there is anything first in the $_COOKIE before print it

if(isset($_COOKIE['id']) && isset($_COOKIE['pwd'])){
    print "Your ID: " . $_COOKIE['id'] . '<br>';
    print "Your PASS: ". $_COOKIE['pwd'] . '<br>';
}

your code will be like this

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST') {

    $id = $_POST["id"];
    $pwd = $_POST["pass"];

    if (isset($_POST["chkbx"])){
        setcookie("id", $id ,time()+3600);        
        setcookie("pwd", $pwd, time()+3600);
    }
}

if(isset($_COOKIE['id']) && isset($_COOKIE['pwd'])){
    print "Your ID: " . $_COOKIE['id'] . '<br>';
    print "Your PASS: ". $_COOKIE['pwd'] . '<br>';
}
?>


<html>
<head>
    <title>
        Remember Me
    </title>
</head>
<body>
    Please Enter ID and PASS
    <form method="post" >
       Enter ID
        <input type="text" name="id" value="<?= isset($_COOKIE['id'])? $_COOKIE['id']: '' ?>" />
       Enter PASS
        <input type="text" name="pass" value="<?= isset($_COOKIE['pwd'])? $_COOKIE['pwd']: '' ?>" />
   <input type="submit" value="submit" /><br>
   <input type="checkbox" name="chkbx" />Remember Me
   <input type="hidden" name="chk" value="true" />
    </form>
</body>
</html>

Upvotes: 1

Related Questions