【问题标题】:Not able to set cookies from form with php无法使用 php 从表单设置 cookie
【发布时间】:2018-04-07 15:49:59
【问题描述】:

我已经检查了很多次代码,但无法找到错误! issetCookie 在这里返回 false。

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

谁能帮我为 cookie 分配变量? 如果是其他问题,请建议使用表单数据分配 cookie 值并在表单操作中定义的下一页上检索的替代选项。

【问题讨论】:

标签: php html forms cookies


【解决方案1】:

因为您试图在else 条件中设置cookie。所以变量在其他条件下不存在,因为未提交表单。你需要像这样添加过期时间。

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

然后像这样检查

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

你的代码应该是这样的

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

【讨论】:

  • 再次刷新页面
  • 您试图在不正确的其他条件下设置 cookie
  • 因为当你提交表单时,值是存在的,但在 else 条件下不存在
  • 我正在尝试使用 javascript 来设置 cookie。这样我就不需要使用 if...else
  • 其他条件下不存在值
【解决方案2】:

像这样使用。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-02
    相关资源
    最近更新 更多