【问题标题】:How to insert the information of a cookie in a form如何在表单中插入 cookie 的信息
【发布时间】:2017-05-19 15:23:51
【问题描述】:

我的 php 脚本有问题。我想将我的 cookie 的值打印为我创建的表单中的“值”。但它不打印它,我的网站看起来不像我想要的。这是我的代码。我得到的错误是: 注意:未定义索引:第 4 行 C:\xampp\htdocs\OpenClassroom\index.php 中的伪

提前致谢。

<?php
if (isset($_COOKIE['username']))
{
    setcookie('username', htmlspecialchars($_POST['pseudo']), time() + 31536000, null, null, false, true);
}
else
{
    setcookie('username', 'NewUsername', time() + 365*24*3600, null, null, false, true);
}
?>
    
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Mini-chat</title>
    </head>
    <style>
    form
    {
        text-align:center;
    }
    </style>
    <body>
    <!--Form-->
    <form action="commentaires.php" method="post">
        <p>
        <label for="pseudo">Pseudo</label> : <input type="text" value="<?php echo $_COOKIE['username'] ; ?>" name="pseudo" id="pseudo" /><br />
        <label for="message">Message</label> :  <input type="text" name="message" id="message" /><br />

        <input type="submit" value="Envoyer" />
	</p>
    </form>

【问题讨论】:

  • 启用error_reporting(E_ALL); 后会出现哪些错误。 cookie 设置好了吗?在你的浏览器中检查这个
  • 我有这个错误:注意:未定义的索引:第 4 行 C:\xampp\htdocs\OpenClassroom\index.php 中的伪

标签: php html cookies


【解决方案1】:

根据文档,$_COOKIE 在第一次请求中使用setcookie() 时不设置cookie:

一旦设置了 cookie,就可以在下一页加载时使用 $_COOKIE 数组访问它们。 Cookie 值也可能存在于 $_REQUEST 中。

所以...后续请求将正确显示。一个快速而肮脏的解决方案是第一次手动设置:

<?php
if (isset($_COOKIE['username']))
{
    setcookie('username', htmlspecialchars($_POST['pseudo']), time() + 31536000, null, null, false, true);
}
else
{
    setcookie('username', 'NewUsername', time() + 365*24*3600, null, null, false, true);
    $_COOKIE['username'] = 'NewUsername';
}
?>

【讨论】:

  • 嗨!谢谢你的帮助。我按照你说的做了,现在我有一个启动 cookie,但是当我改变我的“伪”时,cookie 应该会改变,但它不会。你能帮帮我吗?
  • 代码还有其他一些问题。完整的对话可以找到here
猜你喜欢
  • 2010-12-18
  • 1970-01-01
  • 2013-12-30
  • 1970-01-01
  • 2015-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多