使用PHP中的cookie打印历史记录

时间:2016-12-15 06:51:05

标签: php html css cookies

<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";
}
?>

我想打印输入的最后十个名字。如何做到这一点我不知道请帮助我?

1 个答案:

答案 0 :(得分:0)

如果要保存同一用户的最后10个,可以使用序列化将数组保存在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;   
}