1

I'm new at PHP and although i found similar solutions for this error, i cannot solve it yet. When running this page i get the error: Notice: Undefined index: NameFilledIn in C:\xampp\htdocs\vdab\cookies.php on line 9. When I fill in a name and refresh the page, it does work. Once the time of the cookie is passed and I refresh the page, I get the same error as in the beginning.

The complete code is:

<?php
 if (!empty($_POST["txtName"]))
     {
      setcookie("NameFilledIn", $_POST["txtName"],time() + 60);
      $name = $_POST["txtName"];
     }
     else
     {
      $name = $_COOKIE["NameFilledIn"];
     }
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org /TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
<?php
  if (isset($name))
  {
   print ("Welcom, ") . $name;
  }
?>
  <form action="cookies.php" method="POST">
  Uour name: <input type="text" name="txtName" value="<?php print ($name);?>">
  <input type="submit" value="Send">
  </form>

<br><br>
<a href="cookies.php">Refresh the page</a>
</body>
</html>
Carl
  • 11
  • 4
  • It's not an error, its a notice ;) probaly because the value isn't set – Azrael Sep 22 '14 at 09:44
  • 1
    possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Gerald Schneider Sep 22 '14 at 09:44

1 Answers1

1

The notice Undefined index: occurred because you are trying to access cookie without checking whether it is set or not. Use isset() to check if they are declared before referencing them like,

 if (!empty($_POST["txtName"]))
     {
      setcookie("NameFilledIn", $_POST["txtName"],time() + 60);
      $name = $_POST["txtName"];
     }
     else
     {
       if(isset($_COOKIE["NameFilledIn"]))   // only if it is set
         $name = $_COOKIE["NameFilledIn"];
     }

The same thing you have to check everywhere you are trying to echo/access the PHP variables.

<input type="text" name="txtName" value="<?php if(isset($name)) { print ($name); } ?>">
Jenz
  • 8,280
  • 7
  • 44
  • 77
  • It's almost working 100%. Why is it that, after the field where you fill in your name, something like
    Notice: Undefined variable: name in C:\xampp\htdocs\cookies.php on line 26
    is filled in? How to empty that?
    – Carl Sep 22 '14 at 10:07