Set up cookie for page visit - php

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']);

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']));

use this:
$lastTime = date('d-M-Y');
and not this:
$lastTime = date('d-M-Y H-i-m-s');

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')){...

Related

Avoid loop for Date add by day?

I am using Carbon to add number of days, it there a way to avoid using for and/or while loop?
Add the numbers of days ($skipDayBy) and add the number of days if found in $excludeDatesPublic or $excludeDatesManual?
For example working demo:
function calculateDate($skipDayBy = 0) {
$excludeDatesPublic = ['2019-08-28'];
$excludeDatesManual = ['2019-09-01'];
$date = Carbon::now();
for($i = 0; $i < $skipDayBy; $i++) {
$date = $date->addDays(1);
while(in_array($date->toDateString(), $excludeDatesPublic) || in_array($date->toDateString(), $excludeDatesManual))
{
$date = $date->addDays(1);
}
}
return $date->toDateString();
}
echo calculateDate(4);
Returned 2019-09-02 as expected if today date is 2019-08-27.
Maybe you're looking for https://github.com/kylekatarnls/business-day that allows you to add days skipping holidays.
Alternatively, you can use the periods:
$skipDayBy = 5;
$excludeDatesPublic = ['2019-09-01'];
$excludeDatesManual = ['2019-09-04'];
$exclude = array_merge($excludeDatesPublic, $excludeDatesManual);
$date = CarbonPeriod::create(Carbon::now(), $skipDayBy)
->addFilter(function (Carbon $date) use ($exclude) {
return !in_array($date->format('Y-m-d'), $exclude);
})
->calculateEnd();
var_dump($date); // 2019-09-06 18:50:17 if run at 2019-08-31 18:50:17
With PHP shortly
$day='2019-12-12';
$date = date('Y-m-d', strtotime($day . " +4 days"));
echo $date;
Output
2019-12-16
Or u can use
$date= date('Y-m-d', strtotime('+4 days', strtotime($day)));

Check if weekday is between weekdays in string

So i have a list of weekdays in which i need to check if they are the current day. The list varies between either being 'Monday/Tuesday' and 'Wednesday - Friday'
My current solution is string comparison, so it only detects if the current weekday is written in the list item.
Heres the current solution (in PHP btw):
setlocale(LC_ALL, "danish");
$day = get_sub_field('dag'); // the field containing the user input day
$currentDay = strftime('%a', mktime());
$currentDayLower = strtolower($currentDay);
$dayLowercase = strtolower($day);
$class = '';
if(strpos($dayLowercase, $currentDayLower) !== false ){
$class = ' current-day';
} else{
$class = '';
}
I was thinking about having an array of all weekdays and comparing the user field to current day position in the array, but im not sure if that would be efficient or even possible.
Is there any obvious or alternative method that could be easier than what I'm currently doing?
Any inputs are greatly appreciated.
EDIT:
I found a working solution, which i posted as an answer (I can't choose it as the answer for 2 days though). Thanks for the inputs!
Yes, your idea is feasible and it should not affect performance badly unless you do this many times in a short period of time, where many starts at a scale of hundreds of thousands. Notice that I have created an array of $weekdays and notice that when you assign a value for $class, that is an end sign for the cycle as well.
setlocale(LC_ALL, "danish");
$day = get_sub_field('dag'); // the field containing the user input day
$dayLowercase = strtolower($day);
$weekdays = array("monday", "tuesday", "wednesday", "thursday", "friday");
$class = '';
for ($index = 0, (!$class) && ($index < 5); $index++) {
if(strpos($dayLowercase, $weekdays[$index]) !== false ){
$class = ' current-day';
} else{
$class = '';
}
}
If you want to check that the range of days includes the current day, you can do the following.
$period = 'Wednesday-Friday';
$limitDays = explode('-', $period);
$startDayName = trim(strtolower($limitDays[0]));
$endDayName = trim(strtolower($limitDays[1]));
$today = new DateTime();
$todayName = strtolower($today->format('l'));
// Check if the startDay or endDay is today.
echo "$startDayName $endDayName $todayName\n";
if ($startDayName === $todayName || $endDayName === $todayName) {
echo "Same day\n";
$class = 'current-day';
} else {
// Get a date time representing the start day.
$startDay = new \DateTime();
$startDay->modify("next $startDayName");
// Based on the start day, get the next current day.
$thisDay = new \DateTime();
$thisDay->modify("next $startDayName");
$thisDay->modify("next $todayName");
// Based on the start day, get the next end day.
$endDay = new \DateTime();
$endDay->modify("next $startDayName");
$endDay->modify("next $endDayName");
// Check if thisDay is between the startDay and endDay.
if ($startDay < $thisDay && $thisDay < $endDay) {
$class = 'current-day';
} else {
$class = '';
}
}
echo $class . "\n";
I'm not sure that this is easier or more efficient, but it's not a bad way to do this.
So as i found out, its rather complicated making a datetime from a Danish weekday string. A lot easier to go from English and format to Danish.
So i had to make it a bit different, by stitching parts of you guys' answers together.
<?php while ( have_rows('aabningstider_repeater', 'option') ) : the_row();
// vars
$day = get_sub_field('dag');
$timer = get_sub_field('aabne_timer');
$dayLower = strtolower($day);
$weekArray = array('mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag', 'søndag' );
$dayArray = preg_split('/[\s,-]+/', $dayLower);
$today = date('w') - 1;
$class = '';
if(is_array($dayArray)){
$days = [];
foreach ($dayArray as $daySingle ) {
array_push($days, array_search($daySingle, $weekArray));
}
if($today > $days[0] && $today < $days[1]){
$class = ' current-day in-between-days';
} elseif($today == $days[0] || $today == $days[1]){
$class = ' current-day';
} else{
$class = '';
}
}
endwhile; ?>
I'm pretty sure this will work untill i one day detect a major flaw. Until then it'll do.
Any feedback or optimization is greatly appreciated. And thanks for all the inputs!
setlocale(LC_ALL, "danish");
$day = get_sub_field('dag'); // the field containing the user input day
$currentDayLower = strtolower(date("D"));
$dayLowercase = strtolower($day);
$class = '';
if($dayLowercase === $currentDayLower)
$class = ' current-day';

convert string array to integer php

Question:
How the best to convert $p=' "'.implode('","', $person).'"'; $p to an integer?
What I have:
I am trying to use an if statement telling $person == false;
$x['date']; is the timestamp in my database.
I have worked out the time difference, now I am trying to make the person disappear if post over 3 seconds.
so I used $t > 3 seconds then the $p == false;
The difficulty for my was the $t was implode so it a single string. I was trying to use preg_match, but I don't think this is a good idea.
I am trying to use $difference = settype($t, "integer"); but I am getting a boolean rather than a number.
$diff = array();
$person = array();
foreach($stmt as $x)
{
$person[] = $x['names']. $x['ages'];
$posts[] = $x['date'];
$timePosted = new DateTime($posts[] = $x['date']);
echo 'Time Posted : '. $timePosted ->format("d-m-Y H:i:s");
echo "</br>";
date_default_timezone_set('Europe/London');
$today = date('d-m-Y H:i:s');
echo 'Current time is : '. $today;
echo "</br>";
$today = new DateTime(date('d-m-Y H:i:s'));
$interval = $timePosted->diff($today);
"Difference " . $interval->d. " days ". $interval->h. " hours ".$interval->i." minutes ".$interval->s." seconds ";
echo "</br>";
$diff[] = $interval->h. " hours ".$interval->i." minutes ".$interval->s." seconds ";
$diff[] = $interval->s; //last array seconds
}
$p=' "'.implode('","', $person).'"';
echo $t= ' "'.implode('","', $diff).'"'."<br />";
$difference = settype($t, "integer");
echo gettype($difference);
echo "</br>";
if( $t >3){
$p == false;
}else{
echo "its okay, smaller than 3 seconds";
}
The problem is you're setting $difference = settype($t, "integer");
The settype function returns a boolean. The value $t should be set to an integer, so to test, use echo gettype($t); instead of echo gettype($difference);
also, you're using a comparison operator instead of the assignment in
if( $t >3){
$p == false;
it should be
if( $t >3){
$p = false;

Check if date is within range in PHP strtotime

I have searched through SO but the answers that I've tried doesn't seem to solve my problem.
I have this simple code snippet where the user will input a numeric date, and a month, and the app will return the corresponding Zodiac Sign.
$birthdate = $_POST["birthdate"];
$birthmonth = (ucwords(strtolower($_POST["month"])))
//validations here. . .
$tmp = $birthmonth . " " . $birthdate;
$tmp2 = date_create_from_format('M j', $tmp);
$formatted_dob = date_format($tmp2, 'm-d-Y');
$dob = strtotime($formatted_dob);
echo $formatted_dob;
if ($dob >= strtotime('01-20-2016') && $dob <= strtotime('02-18-2016')) {
echo "Aquarius";
} elseif ($dob >= strtotime('02-19-2016') && $dob <= strtotime('03-20-2016')){
echo "Pisces";
}
Those echo stuff outside the if-else block are working fine, however if I input a value of 25 and February (which later on results to 02-25-2016), it always output Aquarius. How do you compare two strtotimevalues?
I've tried using DateTime object but it only gives me an error, which is another story. Thanks in advance.
Edited:
Change the order of your date (*your format on your date 01-20-2016 m-d-Y that's why when you convert it it becomes 1970-01-01 'Y-m-d' but if you change it into 2016-01-20 'Y-m-d' on your date range the code will work just fine in else-if.
$birthdate = $_POST["birthdate"];
$birthmonth = (ucwords(strtolower($_POST["month"])))
//validations here. . .
$tmp = $birthmonth . " " . $birthdate;
$tmp2 = date_create_from_format('M j', $tmp);
$formatted_dob = date_format($tmp2, 'm-d-Y');
$dob = strtotime($formatted_dob);
echo $formatted_dob;
$dobcompare = date_create(date('m/d/Y', $dob));
$aqstartdate = date_create(date('m/d/Y', strtotime('2016-01-20')));
$aqenddate = date_create(date('m/d/Y', strtotime('2016-02-18')));
$pistartdate = date_create(date('m/d/Y', strtotime('2016-02-19')));
$pienddate = date_create(date('m/d/Y', strtotime('2016-03-20')));
if ($dobcompare >= $aqstartdate && $dobcompare <= $aqenddate) {
echo "Aquarius";
}
elseif ($dobcompare >= $pistartdate && $dobcompare <= $pienddate) {
echo "Pisces";
} else {
echo "IDK";
}
Modify it in your need.
This is the example enter link description here

PHP Day count function writing

I need to Write a function named countDays which takes a single parameter named dateinstring which is string in the form ”MM.DD.YYY” represent a real date value. The function should print to the console the number of days from the beginning of the year specified in dateInString until the date represented in dateInString. If the value of dateInString is invalid, the function should print ”Bad format” to the console.
I have written the code as below :
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = $date[2].'-'.$date[0].'-'.$date[1].'00:00:00';
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
echo round($diff/86400)+1;
}
else {
echo 'Bad format';
}
};
countDays('1.15.2014');
But the above code seems that not giving the correct output. It is about 33% correct. But where is the problem with this code ? Please help me!!!
$diff = strtotime($formatted_date).'-'.strtotime($date[2].'-01-01 00:00:00');
Change to
$diff = strtotime($formatted_date) - strtotime($date[2].'-01-01 00:00:00');
You made the minus symbol a string instead of an operator.
You could try it this way
function countDays($dateInString) {
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if (checkdate($date[0], $date[1], $date[2])) {
$year_start = mktime(0, 0, 0, 1, 1, $date[2]);
$your_date = mktime(0,0,0,$date[0], $date[1], $date[2]);
$diff = $your_date - $year_start;
echo floor($diff /(60*60*24));
} else {
echo "Bad date supplied";
}
}
A better approach would be to use the DateTime class. I haven't included the validation in this, but i suggest you use regex for that.
function countDays($dateInString){
$parts = explode('.', $dateInString);
$date = new DateTime($parts[2] . '-' . $parts[0] . '-' . $parts[1]);
$compare = new DateTime( $date->format('Y') . '-01-01' );
$interval = $date->diff($compare);
return $interval->format('%a');
}
echo countDays('09.15.2014');
Check this out.
function countDays($dateInString){
date_default_timezone_set('America/Los_Angeles');
$date = explode('.', $dateInString);
if(count($date) == 3 && checkdate($date[0], $date[1], $date[2])){
$formatted_date = strtotime($date[2].'/'.$date[0].'/'.$date[1]);
$endTimeStamp = strtotime("2014/01/01");
$timeDiff = abs($endTimeStamp - $formatted_date);
echo round(intval($timeDiff/86400));
}
else {
echo 'Bad format';
}
};
countDays('01.01.2014');

Categories