Reputation: 35
I want to set up 2 cookies. One that shows how many times a user entered the page, and the other shows the date and the time of last visit.
The code works fine, but I need my cookies set up once a day, not every time I visit the page. What I need is to set the if($_COOKIE['lastTime'] != date('d-M-Y'))
statement, but I need to compare only the 'd-M-Y' part of $_COOKIE['lastTime']
. Also, I can't set $lastTime = date('d-M-Y')
(without h-i-m-s), because I need to show the date AND the time of last visit.
Please, help.
$counter = 0;
if(isset($_COOKIE['counter'])){
$counter = $_COOKIE['counter'];
}
$counter++;
$lastTime = '';
if(isset($_COOKIE['lastTime'])){
$lastTime = $_COOKIE['lastTime'];
}
$lastTime = date('d-M-Y H-i-m-s');
if($_COOKIE['lastTime'] != date('d-M-Y')){
setcookie('counter', $counter);
setcookie('lastTime', $lastTime);
}
print_r('This is your ' . $_COOKIE['counter'] . ' visit');
echo '<br>';
print_r('Last visit was: ' . $_COOKIE['lastTime']);
Upvotes: 2
Views: 187
Reputation: 12910
I left commented lines in the scope, so you can see what can be optimised to get brevity to your code. Those commented lines are not needed at all.
print_r('Previous visit was: ' . isset($_COOKIE['lastTime'] ? date("Y-m-d", $_COOKIE['lastTime']) : 'not set yet'));
$counter = 0;
if(isset($_COOKIE['counter'])){
$counter = $_COOKIE['counter'];
}
$counter++;
$lastDay = '';
if(isset($_COOKIE['lastTime']) {
$lastDay = date("Y-m-d", $_COOKIE['lastTime']);
}
$currentDay = date("Y-m-d");
if(!$lastDay || $lastDay < $currentDay) {
setcookie('counter', $counter);
setcookie('lastTime', strtotime($currentDay));
}
print_r('This is your ' . $_COOKIE['counter'] . ' visit');
echo '<br>';
// here you print a readable datetime format from your stored date
print_r('Last stored visit date was: ' . date("Y-m-d", $_COOKIE['lastTime']));
Upvotes: 1
Reputation: 361
Your code:
$lastTime = '';
if(isset($_COOKIE['lastTime'])){
$lastTime = $_COOKIE['lastTime'];
}
$lastTime = date('d-M-Y H-i-m-s'); <-- you're overwriting any retrieved value here
Check if you got a value first so you don't overwrite it, and then extract just the date part:
$lastTime = '';
if(isset($_COOKIE['lastTime'])){
$lastTime = $_COOKIE['lastTime'];
}
if(strlen($lastTime) == 0)
$lastTime = date('d-M-Y H-i-m-s');
$parts = explode(" ", $lastTime);
$lastDay = $parts[0];
if($lastDay != date('d-M-Y')){...
Upvotes: 0
Reputation: 10498
use this:
$lastTime = date('d-M-Y');
and not this:
$lastTime = date('d-M-Y H-i-m-s');
Upvotes: 0