I'm trying to implement the following feature. When someone reads an article, I want to add a cookie that stores the article id so I can use this in another page. My issue is that if the user sees another article, then the cookie is rewritten so the old id is deleted. I want to keep in the cookie all the ids of the seen articles.
Setting the cookie
<?php
// Check if cookie exists
if( isset($_COOKIE["read"]) ) {
$array = unserialize($_COOKIE['read']);
// Iterate array
found = False;
foreach ($array as $i) {
// Check if doc id already in cookie
if ($array[$i] == $id) {
found = True;
}
}
if (!found) {
array_push($array, $id);
setcookie("read", serialize($array), time()+3600);
}
}
// If cookie does NOT exists
else {
$array = array();
array_push($array, $id);
setcookie("read", serialize($array), time()+3600);
}
?>
Reading the cookie to show that the article is read
<?php
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
if( isset($_COOKIE["read"]) ) {
$array = unserialize($_COOKIE['read']);
// Iterate array
for ($i = 0; $i < count($array); ++$i) {
if ($array[$i] == $id) {
$read = True;
}
else {
$read = False;
}
}
}
else {
$read = False;
}
print "<p>Document ".$row['id']." Title: <b>".$row['title']."</b>";
if ($read == True) {
print("*");
}
print " <a href=\"detail.php?id=".$row['id']."\">More Info</a></p>";
}
?>
This code works but as said overwrites the previous article id. I think I got to use an array. But I don't know how to keep adding values.
UPDATE: I tried to serialize
but still no results. I'm trying to see if the id
is inside the unserialized
array.