【问题标题】:Printing the history using cookies in PHP在 PHP 中使用 cookie 打印历史记录
【发布时间】:2016-12-17 18:36:30
【问题描述】:
<html>
    <head>
        <meta charset="UTF-8">
        <title> Cookies </title>
    </head>
    <body>
<h1> Cookies Concept </h1>
        <form method="get" action="index.php">
           Enter Your Name:  <input type="text" name="name">
            <input type="submit" name="done"> 
        </form>
    </body>
</html>
<?php
if(!empty($_GET['name']))    
{
    if(empty($_COOKIE['name']))
    {
        setcookie('name',$_GET['name']."<br",time()+86400);
    }
   else 
    {
        setcookie('name',$_GET['name'].<br>".$_COOKIE['name'],time()+86400);    
    }    
}    
if(isset($_COOKIE['name']))
{
        echo $_COOKIE['name'];
}
else 
{
    echo "Cookie cannot be set";
}
?>

我想打印最后输入的十个名字。我不知道该怎么做,请帮助我?

【问题讨论】:

  • 你不能。除非您也将它们存储在其他地方,否则不会。 Cookie 存储在用户的计算机上,而不是服务器上。您不可能同时访问最后 10 个 cookie,或者如果您这样做(即,如果有超过 10 个并发用户,那么提取他们所有的 cookie、编造它并在一个上显示它会很麻烦网站(您必须为所有页面上的所有用户提取 cookie 并过滤掉最后 10 个)。忘掉它,找到另一种方法来做你想做的事。
  • 正是@junkfoodjunkie 所说的。另外我想补充一点,任何人都可以轻松地操纵$_COOKIE 函数设置的cookie。因此,如果您真的想使用$_COOKIE 而不是会话,请确保您还设置了允许的路径、域和 HttpOnly 参数。

标签: php html css cookies


【解决方案1】:

如果您想保存来自同一用户的最后 10 个,您可以使用 serialize 在 cookie 中保存一个数组。但请记住,这不会在用户之间共享信息,因为 cookie 仅适用于该访问者。 例如:

if(isset($_GET['name'])){ #get the name   
  $name = strip_tags($_GET['name']);
  $names = []; # just names in case there is no names array
  if(isset($_COOKIE['cookie'])){ #read cookie    
    $names = unserialize($_COOKIE['names']);    
  }   

  array_unshift($names, $name); #put the name in begging of the list 

  if(count($names) > 10 ){ #remove last entry if have more then 10   
    array_pop($names);    
  }  
  setcookie('names', serialize($names), time()+3600);
}

//to print just read cookie and  
foreach($names as $name ){   
  echo $name;   
}

【讨论】:

    猜你喜欢
    • 2019-04-30
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    相关资源
    最近更新 更多