<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";
}
?>
我想打印输入的最后十个名字。如何做到这一点我不知道请帮助我?
答案 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;
}