1

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
manosim
  • 3,630
  • 12
  • 45
  • 68

2 Answers2

1

Do you want Arrays in cookies PHP

Serialize data:

setcookie('cookie', serialize($idS));

Then unserialize data:

$idS= unserialize($_COOKIE['cookie']);
Community
  • 1
  • 1
Abdullah
  • 627
  • 9
  • 27
  • I tried to use serialize but I still can't make it work. I think I can't search in the array. Can you have a look at the updated code? Thanks! – manosim May 17 '14 at 23:56
0

Try adding a datetime() string to the start of the cookie's name. That way old ones won't get overwritten. Something like:

$date_snippet = date('Y-m-d H:i:s'); 
setcookie("{$date_snippet}read", serialize($array), time()+3600);
Hektor
  • 1,845
  • 15
  • 19