Reputation: 35
I want to display how many days/hours/minutes/seconds ago a user last visited the website. I'm new to cookies and can't get to make them work.
Edit: Right now $lastVisit
and $thisVisit
are the same, how would i make them separate?
Here's my code so far (I know it's doing nothing close to what it's supposed to do):
<?php
if(isset($_COOKIE['LastCookie']))
{
$lastVisit = $_COOKIE['LastCookie'];
$inOneMonth = time() + (60*60*24*30);
setcookie('LastCookie', time(), $inOneMonth);
$thisVisit = $_COOKIE['LastCookie'];
?>
<html>
<head>
<title>Cookie Exercise</title>
</head>
<body>
<p> Your last visit was before: </br /></p>
<?php
echo $lastVisit."<br />";
$diff = $thisVisit - $lastVisit;
$seconds = $diff % 60;
$minutes = $seconds % 60;
$hours = $minutes % 60;
$days = $hours % 24;
echo "Diff: $diff <br /> $days $hours $minutes $seconds";
?>
</body>
</html>
<?php
}
else
{
setcookie('LastCookie', time(), time() + (60*60*24*30));
?>
<html>
<head>
<title>Cookie Exercise</title>
</head>
<body>
<p> This is your first visit to this website </br /></p>
</body>
</html>
<?php
}
?>
Here's the exercise I'm trying to do incase my explaination wasn't clear:
Upvotes: 0
Views: 1019
Reputation: 675
As i see, you don't set the cookie, you just check if the cookie exists.
To save a cookie use setcookie
:
setcookie('test', 'Hello!', time()+(60*60*24), '/');
This function will set a cookie with the name test
and the value Hello!
expiring 24 hours after the cookie was set. The /
at the end is the path. Use /
, if you want to access the cookie on your whole page, use for example /test/
if you only want to use it in the test
directory.
Use isset()
to check, if a cookie already exists:
if( isset($_COOKIE['test']) ) {
// Cookie exists
}
To get the cookie's content, use:
$test = $_COOKIE['test'];
If you want to update the expiration date, just overwrite the current cookie with the setcookie()
function.
That's also how to delete a cookie, just set the expiration date lower than the current timestamp.
Upvotes: 0
Reputation: 944474
You have this condition:
if(isset($_COOKIE['LastCookie']))
As a prerequisite to this line of code:
setcookie('LastCookie', time(), $inOneMonth);
… so you only ever update an existing cookie. You never set a new one if this is the first visit.
You need to calculate $lastVisit
if the cookie is set, but set the new cookie regardless (outside of the condition).
Upvotes: 1