<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";
}
?>
I want to print the last ten name entered . How to do this I don't know please help me ?
If you want to save the last 10 from the same user you can use serialize to save an array in the cookie. But remember that will not share info between users since cookie is just for that visitor. For example:
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;
}