0

I have checked the code many times, yet not able to find the error! the issetCookie returns false here.

<html>
 <body>
   <?php if(!isset($_REQUEST['sub'])) { ?>
   <form name="f1" action="1.php" method="post">
     Name : <input type="text" name="na"><br>
     Last Name : <input type="text" name="lna"><br>
     Email Id : <input type="text" name="eml"><br>
     Phone No : <input type="text" name="phn"><br>
     City : <input type="text" name="cty"><br>
     <input type="Submit" name="sub" value="ok"><input type="Reset" name="res" value="Clear">
  <?php } else {
     $name=$_REQUEST['na'];
     $lname=$_REQUEST['lna'];
     $email=$_REQUEST['eml'];
     $phone=$_REQUEST['phn'];
     $city=$_REQUEST['cty'];

     setcookie("Name", $name, time()+3600, "/","", 0);
     setcookie("LName",$lname);
     setcookie("Email",$email);
     setcookie("Phone",$phone);
     setcookie("City",$city);
  } ?>
  </form>
 </body>
</html>

Can someone help me to assign variables to cookie? If its the issue of else, please suggest alternate options of assigning cookie value using form data and retrieving on the next page defined in form action.

2 Answers2

0

because you are trying to set cookies in else condition.so variables are not exist in else condition because form is not submitted. and you need to add expire time like this.

setcookie("Name", $name, time() + (86400 * 30), "/");// one day

and check like this

if(!isset($_COOKIE['Name'])) {
         echo "Cookie named  is not set!";
    } else {
         echo "Cookie  is set!<br>";
         echo "Value is: " . $_COOKIE['Name'];
    }

your code should be like this

<?php
if (isset($_POST['sub'])) {
    $name=$_POST['na'];
    $lname=$_POST['lna'];
    $email=$_POST['eml'];
    $phone=$_POST['phn'];
    $city=$_POST['cty'];
    setcookie("Name", $name, time() + (86400 * 30), "/");
}
if(!isset($_COOKIE['Name'])) {
     echo "Cookie named  is not set!";
} else {
     echo "Cookie  is set!<br>";
     echo "Value is: " . $_COOKIE['Name'];
}
?>
<html>
<body>
     <form name="f1" action="1.php" method="post">
     Name : <input type="text" name="na"><br>
     Last Name : <input type="text" name="lna"><br>
     Email Id : <input type="text" name="eml"><br>
     Phone No : <input type="text" name="phn"><br>
     City : <input type="text" name="cty"><br>
     <input type="Submit" name="sub" value="ok"><input type="Reset" 
     name="res" 
     value="Clear">
    </form>
</body>
</html>
Rahul
  • 1,617
  • 1
  • 9
  • 18
0

use like this.

$cookie_name = "name";
$cookie_value = $_REQUEST['na'];
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
Gorakh Yadav
  • 304
  • 5
  • 19