【问题标题】:Setting a cookie from a php post form从 php post 表单设置 cookie
【发布时间】:2013-02-01 20:30:38
【问题描述】:

我正在尝试获取一个 php 表单以从 cookie 中自动填充用户 ID 字段,或者如果它是一台新电脑,则为用户提供“记住我”的选项。当我手动添加 cookie 然后加载表单页面时,它会正确填充用户框,但是当它从表单本身发布时,我似乎无法设置 cookie。

来自 php 表单的代码:

<form action="./post_cookies.php" method="post" id="HOME">
    <div id="nav">
        <ul>
            <li><i>Whats your username:</i></li>
           <li><i><input type="text" size="40" name="User_ID" 

           <?php
if (isset($_COOKIE["user"]))
  echo "value=\"" . $_COOKIE["user"] . "\"</i></li>";
else
  echo "placeholder=\"12345\"></i></li>";
?> 
            <li><i>Remember me: <INPUT TYPE="checkbox" NAME="remember" VALUE="1"> Yes</i></li>
        </ul>
    </div>

<div id="nav" style="text-align:center;">
        <ul>
            <li><i><button form="HOME" type=submit style="width:200px;height:40px">Submit</button></i></li>
        </form>
        </ul>
    </div>

</div>

此表单发布到“post_cookies.php”,代码为:

   <?php
// creating a variable to store the timestamp in
$posttime = time();

// if the remember me checkbox returns a 1 then add the users, username as a cookie

if($_POST[remember]==1)
{   
    setcookie('user', $_POST[User_ID], $posttime + 3600);        // Sets the cookie 
}

// this is where the data base connection would go

header("Location: http://www.domain.com/index.php");
?>

这个想法是,如果“记住我”被选中,那么 post_cookies.php 将使用用户 ID 设置一个 cookie。

我看不到 post_cookies.php 哪里出了问题,也没有设置 cookie。 非常感谢任何帮助。

谢谢! 马修

【问题讨论】:

    标签: php post cookies


    【解决方案1】:

    应该是:

    if ($_POST['remember'] == 1) {   
        setcookie('user', $_POST['User_ID'], $posttime + 3600);        // Sets the cookie 
    }
    

    数组键用引号括起来。试试看

    相同
    $_POST['User_ID']
    

    还有

    echo "value=\"" . $_COOKIE["user"] . "\"</i></li>";
    

    &lt;/i&gt; 之前缺少结束&gt;

    【讨论】:

    • 仍然无法加载cookie,我修改了两个文件并输入:'' 尝试查看我是否可以读取提供的 cookie,但仍然是空白。
    • 如果我在 if 条件中使用 $_POST,那么 if 块中的 setcookie 不会设置 cookie,尽管它返回 true。很奇特的东西。吸我。
    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多