【问题标题】:How to store a value in a cookie and then echo it如何在 cookie 中存储一个值然后回显它
【发布时间】:2017-07-18 19:07:52
【问题描述】:

我看了类似的问题,但还是不行。

我正在尝试做的是,例如,用户输入他的姓名/城市,我希望将此数据存储在 cookie 中,下次他进入页面时会显示消息"Hello [name] from [city]."

我试过了

$_COOKIE['name']=$_POST['name'];
after the form and at the beginning I put
if(!empty($_COOKIE['name']))
echo "Hello" . $_COOKIE['name'];

无论如何,代码比这要大一些,但基本上这就是我想要做的。什么都没有出现。是的,在我验证用户使用 if(!empty($_POST)) 完成每个输入后,我使用了 setcookie。

【问题讨论】:

  • 你是在使用 Angular 还是 jQuery 之类的 cookie?
  • “是的,我使用了 setcookie”——在哪里?提供minimal reproducible example
  • 危险:此代码是vulnerable to XSS 用户输入需要转义才能插入到 HTML 文档中!。
  • “另外,如果你能帮我解决一些与 cookie 无关的问题”——如果你还有其他问题,那么ask another question。不要在不相关的事情的结尾卡住它。另外:不要问广泛的问题。专注于具体问题。
  • 哦,对不起 - 没有看到 PHP。这里只有 JS。只是打算将您指向w3schools.com/js/tryit.asp?filename=tryjs_cookie_username ...无论如何它仍然可能会有所帮助。

标签: php forms cookies


【解决方案1】:

..是的,我使用了 setcookie”。但是,它在提供的代码中是不可见的(或 type='hidden')。

设置 Cookie

/* Set Cookie */
$cookie_duration = 30 * 24 * 60 * 60; // Cookie Duration is for 30 Days. Change it accordingly.

setcookie ("_name", $_POST['name'], $cookie_duration);
setcookie ("_city", $_POST['city'], $cookie_duration);

/* Retreive Cookie */
$name = isset($_COOKIE["_name"]) ? $_COOKIE["_name"] : "";
$city = isset($_COOKIE["_city"]) ? $_COOKIE["_city"] : "";

if($name != "" && $city != ""){
  echo "Hello ".$name." from ".$city.".";
}
?>

取消设置 Cookie

<?php
/* If wanted to remove the cookie after some period of time,
 * Unset Cookie 
 */
setcookie("_name", "", time()-3600);
setcookie("_city", "", time()-3600);

?>

【讨论】:

  • 这完全取决于您的代码功能@Phux。你必须分享你的代码。因为,这就是 cookie 的工作原理。现在,这完全取决于你的逻辑,你是如何实现它的。
  • 没问题很高兴,它为你工作@Phux。继续编码。
【解决方案2】:

你必须使用 setcookie。 http://php.net/manual/en/function.setcookie.php

echo $_COOKIE['foo'] 为您提供名为“foo”的 cookie 的内容。

不要为您需要的每个值都使用一个 cookie。而是考虑将数据作为 JSON 存储在一个数据 cookie 中。

【讨论】:

    猜你喜欢
    • 2010-12-11
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 2010-11-13
    相关资源
    最近更新 更多