Reputation: 993
I have very little experience with cookies so I don't know how to do that.
I have a t-shirt shop where each t-shirt has an $articleID
.
Each time an user visits a t-shirt page, I would like to add the $articleID
to a cookie.
Then add it to an array or something so I can retrieve it later.
There shouldn't be any duplicate $articleID
even if the visitor visited the same $articleID
twice.
Then on the main page, I want to retrieve the list of the last 5 $articleID
visited and display a list of the ID.
How could I do that?
Thanks!
Upvotes: 0
Views: 1176
Reputation: 3911
in order to store an array in your cookies you will need to serialize it so check if this code will help
$articles = array();
if ( isset($_COOKIE["viewed_articles"]) )
$articles = unserialize($_COOKIE["viewed_articles"]);
if ( ! in_array($articleID, $articles)){
$articles[] = $articleID;
}
// at the end update the cookies
setcookie("viewed_articles", serialize($articles));
I hope this helps and have a loop at this link
Upvotes: 2
Reputation: 9547
Something like this?
<?php
$article_id = 1; // Whichever article you're currently viewing
session_start();
if ( ! isset($_SESSION['viewed_articles']))
{
$_SESSION['viewed_articles'] = array();
}
if ( ! in_array($article_id, $_SESSION['viewed_articles']))
{
$_SESSION['viewed_articles'][] = $article_id;
}
Upvotes: 1
Reputation: 463
Have you tried using Sessions? Cookies will store the values on the users computer. That data is transferred to your web server on every page load.
Sessions store data on the server side. Sessions work by storing a session ID as a cookie on the user's browser which corresponds to a session stored on the server.
If you are using PHP, you can initiate a session by using
<?php
session_start();
$_SESSION['key'] = 'value';
echo $_SESSION['key']; // outputs: value
?>
Upvotes: 0