Format GMT date to integer in PHP - javascript

I'm creating a cookie in JavaScript with this code. I actually changed the code a bit:
function setCookie (name,value,days) {
var expires, newValue;
if (days) {
var date = new Date(); // days = 0.0006944444; // testing with one minute
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toString();
newValue = encodeURIComponent(value)+'|'+date+expires;
} else expires = "";
document.cookie = name+"="+(newValue)+"; path=/";
}
So the above function sends encodeURIComponent(value)+'|'+date+expires as value. In PHP I can do explode('|',$_COOKIE['my-key']) with the date formatted like this:
$string_time = "Fri Oct 06 2017 19:34:44 GMT 0300 (Eastern European Summer Time);
Now I need to convert this string to integer to be compared against the PHP's time() integer format.
Doing the following:
$currentTime = date('YmdHis', time());
$expire_time = date('YmdHis', strtotime($string_time));
It actually outputs this:
string(14) "19700101000000" // $currentTime
string(14) "20171006162139" // $cookie_time
Question why is $currentTime always the same 19700101000000 value?

Just use a unix timestamp instead, as you're not getting the time from the expries settings, but from the cookies value
function setCookie (name,value,days) {
var expires, newValue;
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toUTCString();
newValue = date.getTime() / 1000;
} else {
expires = "";
}
document.cookie = name+"="+(newValue)+"; path=/";
}
Now you can compare it directly to the PHP unix timestamp from time() and get the difference in seconds.
Note that you're not even using the expires variable, so this does nothing when it comes to how long the cookie is valid.

Related

PHP can't get cookie that was set in javascript

I am using PHP 8.0 and this is a wordpress site version 6.1.1
I have a plugin that is setting a cookie like so:
window.tourmaster_set_cookie = function( cname, cvalue, expires ){
if( typeof(expires) != 'undefined' ){
if( expires == 0 ){
expires = 86400;
}
var now = new Date();
var new_time = now.getTime() + (parseInt(expires) * 1000);
now.setTime(new_time);
expires = now.toGMTString();
}
document.cookie = cname + "=" + encodeURIComponent(cvalue) + "; expires=" + expires + "; path=/";
}
This is being called like so:
tourmaster_set_cookie('tourmaster-room-cart', JSON.stringify(cart_cookie), 31536000);
I can see in my console log that this cookie is being set.
However when I try to get the cookie in PHP:
$_COOKIE['tourmaster-room-cart']
I get this error:
Warning: Undefined array key "tourmaster-room-cart"
When I do a print_r on $_COOKIE the cookie "tourmaster-room-cart" is not there.
What is going wrong here and how can I fix it?
UPDATE
I created this simple cookie:
document.cookie = "username=John Doe; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";
and it appears in my php $_COOKIE;
However this does not show up in $_COOKIE
window.tourmaster_set_cookie = function( cname, cvalue, expires ){
expires = "Thu, 1 Jan 2026 12:00:00 UTC";
if( typeof(expires) != 'undefined' ){
if( expires == 0 ){
expires = 86400;
}
var now = new Date();
var new_time = now.getTime() + (parseInt(expires) * 1000);
now.setTime(new_time);
expires = now.toGMTString();
}
document.cookie = cname + "=test; expires=Thu, 1 Jan 2026 12:00:00 UTC; path=/";
}
ANOTHER UPDATE
I added a few more cookies to see if they would get displayed with $_COOKIES, they all did except for the last test with encodeURIComponent(cvalue) as the value. It must be something in my value? Here is the updated code and below that is the value.
window.tourmaster_set_cookie = function( cname, cvalue, expires ){
if( typeof(expires) != 'undefined' ){
if( expires == 0 ){
expires = 86400;
}
var now = new Date();
var new_time = now.getTime() + (parseInt(expires) * 1000);
now.setTime(new_time);
expires = now.toGMTString();
}
document.cookie = "newusernameagain=John Doe; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";
document.cookie = "newusername-again=John Doe; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";
document.cookie = "new-username-again=" + encodeURIComponent(cvalue) + "; expires=Thu, 18 Dec 2025 12:00:00 UTC; path=/";
document.cookie = cname + "=" + encodeURIComponent(cvalue) + "; expires=" + expires + "; path=/";
}
And the value
%5B%7B%22start_date%22%3A%222023-02-05%22%2C%22end_date%22%3A%222023-02-06%22%2C%22room_amount%22%3A%221%22%2C%22adult%22%3A%5B%222%22%5D%2C%22children%22%3A%5B%220%22%5D%2C%22room_id%22%3A%2215701%22%2C%22post_type%22%3A%22room%22%7D%5D
I have no idea what is going wrong.
FINAL UPDATE
For some stupid reason when I remove the dashes from the cookie name and where it is referenced everything works. For some odd reason $_COOKIE does not like dashes for the cookie name on this godaddy server, very odd stuff.
If you have passed a correct value (e.g. "SO test") in cart_cookie, then the script should work.
A normal way to set cookie in JS is like:
document.cookie = "username=John Doe; expires=Thu, 1 Jan 2016 12:00:00 UTC";
So assuming the JS script is:
<script>
window.tourmaster_set_cookie = function( cname, cvalue, expires ){
document.cookie = cname + "=" + encodeURIComponent(cvalue) + "; expires=" + expires + "; path=/";
}
tourmaster_set_cookie('tourmaster-room-cart', JSON.stringify('SO test'), "Thu, 1 Jan 2026 12:00:00 UTC");
alert("Done ! Now redirecting to show the cookie string");
window.location.href="testSO5Feb2023c.php";
</script>
On running it , it will set the cookie, and then redirect to another page (I named it testSO5Feb2023c.php), which shows that the cookie is correctly set
For testSO5Feb2023c.php :
<?php
echo "Cookie is now : <br>";
echo $_COOKIE['tourmaster-room-cart'];
?>
You may see the DEMO
Last but not least, please note that the cookie is retrievable ONLY after it is set, so make sure the page to display the cookie is different from the one you set the cookie, otherwise you may need a page refresh
For some stupid reason when I remove the dashes from the cookie name and where it is referenced everything works. For some odd reason $_COOKIE does not like dashes for the cookie name on this godaddy server, very odd stuff.

Calculate end date with number of weeks and disabled dates

I have some data as so from a datepicker:
$disabled_dates = "08/10/2017, 08/17/2017";
$start_date = "08/03/2017";
$num_of_weeks = "20";
I am trying calculate the end date based off the $start_date and $num_of_weeks
I know this is possible with new Date() but i'm not sure how to account for the $disabled_dates.
strtotime() is an amazingly useful function for something like this.
It accepts a wide variety of natural language and date/time inputs.
20 weeks from exactly now
echo date('c',strtotime('+20 weeks'))."\n";
20 weeks from the start of that day
echo date('c',strtotime('08/03/2017 +20 weeks'))."\n";
Your answer in php:
$disabled_dates = "08/10/2017, 08/17/2017";
$start_date = "08/03/2017";
$num_of_weeks = "20";
$the_end = strtotime($start_date.' GMT +'.$num_of_weeks.' weeks');
//make all the disabled dates into timestamps for easy comparison later
$disabled_dates_array = array();
foreach(explode(',', $disabled_dates) as $date){
$disabled_dates_array[] = strtotime(trim($date).' GMT');
}
//now compare and delay the end date if needed
foreach($disabled_dates_array as $timestamp){
//if there was a disabled date before the end, add a day's worth of seconds
//strtotime() returns false if it can't parse the date, so make sure it's truthy
if($timestamp && $timestamp <= $the_end){
$the_end += 86400;
}
}
$enddate = date('m/d/Y',$the_end);
Edit 1: added GMT to all strtotime() conversions, to avoid issues with daylight saving times changing the amount of seconds between dates. Some days are 23 hours and some are 25 because of daylight saving time. Leap seconds are not an issue in unix time.
Edit 2: Answer in javascript:
var disabled_dates = "08/10/2017, 08/17/2017";
var start_date = "08/03/2017";
var num_of_weeks = "20";
var the_end = Date.parse(start_date + ' GMT') + parseInt(num_of_weeks)*7*86400*1000;
//in javascript Date.parse is similar to php's strtotime,
//but it returns milliseconds instead of seconds
disabled_dates = disabled_dates.split(", ");
for(var i = 0, len = disabled_dates.length; i < len; i++){
disabled_dates[i] = Date.parse(disabled_dates[i] + ' GMT');
if(disabled_dates[i] && disabled_dates[i] <= the_end){
the_end += 86400000;
}
}
the_end = new Date(the_end);
var enddate = ('0' + (the_end.getUTCMonth() + 1)).substr(-2) + '/' + ('0' + the_end.getUTCDate()).substr(-2) + '/' + the_end.getUTCFullYear();
console.log(enddate);
Here I ran into a problem with daylight saving time as
Sun Oct 29 2017 00:00:00 GMT+0100 (GMT Daylight Time) + 24 hours =
Sun Oct 29 2017 23:00:00 GMT+0000 (GMT Standard Time)
So adding ' GMT' (GMT Standard Time) at the end of the dates is important, otherwise the results may be off by a day.
This video gives some insight into how keeping time can become complicated.
I'm not sure if there is an easier way, but that's who I would do it:
// Put dates into array or split the string
$disabled = array(new DateTime('2012-08-01'),new DateTime('2017-09-19'));
$end_date = $date->add(new DateInterval('P'.$num_of_weeks.'D'));
$range = new DatePeriod($start_date, new DateInterval('P1D'),$end_date);
// remove disabled days
foreach($range as $date){
if(in_array($date,$disabled))
$end_date = $end_date->sub(new DateInterval('P1D'));
}
The Code is not tested but it should work. If not, let me know xD.
Hope that helps.

Javascript clock with variable timezone

I have a clock like so:
const timeContainer = document.querySelector('.timeContainer');
var showTime = (timeZone) => {
let utcTime = new Date().toUTCString();
//need to subtract/add timezone from utcTime
//need to remove everything except for time e.g. 00:22:22
return utcTime;
};
setInterval( () => {
timeContainer.innerHTML = showTime('-8');
}, 1000);
Which gives me GMT time like this:
Tue, 29 Nov 2016 00:35:54 GMT
.. which is what I want! But say I want to get the time in Hong Kong, and also only the numerical time, none of the date and timezone information.
I basically need to:
a) subtract/add a variable timeZone integer from utcTime
b) remove all text in output except for the time, e.g. utcTime only outputs as 00:22:22
I basically need to generate a clock based on what timeZone integer I run showTime with, for example:
showTime(-5);
//returns time in EST timezone
showTime(-6);
//returns time in CST timezone
etc. Is there a way to do this using .toUTCString()? Or is there a better method?
Here's a jsFiddle with my code.
Get the timestamp which is time since the epoch in UTC, offset by the desired timezone and build the string.
const timeContainer = document.querySelector('.timeContainer');
var dateToTimeString = (dt) => {
let hh = ('0' + dt.getUTCHours()).slice(-2);
let mm = ('0' + dt.getUTCMinutes()).slice(-2);
let ss = ('0' + dt.getUTCSeconds()).slice(-2);
return hh + ':' + mm + ':' + ss;
}
var showTime = (timeZone) => {
// convert timezone in hours to milliseconds
let tzTime = new Date(Date.now() + timeZone * 3600000);
return dateToTimeString(tzTime);
};
setInterval( () => {
timeContainer.innerHTML = showTime('-8');
}, 1000);
jsFiddle
Which will output
17:00:00
If you want the time in the "11/29/2016" format you can use toLocaleDateString() instead of toUTCString().
If you want the time in the "Tue Nov 29 2016" format you can use toDateString() instead of toUTCString().

How to set multiple values with two differents expires dates

I'm trying to set cookie in javascript with two values.
Each of theses have a different expiration date.
For example :
var now = new Date();
now.setDate( now.getDate() + 2 );
document.cookie = "bar=foo;";
document.cookie = "expires=" + now.toUTCString() + ";"
now = new Date();
now.setDate( now.getDate() + 30 );
document.cookie = "foo=bar;";
document.cookie = "expires=" + now.toUTCString() + ";"
Is it correct?
How to set another value with an expiration date for 30 days for example?
I think that approach is correct.
Based on: How can I set a cookie to expire after x days with this code I have? :
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
Note, that setTime() and getTime() work on milliseconds.
And a few words from me: as javascript's Date sucks, I recommend using moment.js library when working with dates, it's brilliant.
Ok, i found my reply here with the function "setCookie". I've specify differents values and it's working.
http://www.w3schools.com/js/js_cookies.asp

Set a cookie expire after 2 hours

I have this JavaScript code:
function spu_createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
How can I make the cookie expire after 2 hours?
If you want to use the same type of function, transform the days param into hours and pass 2 to get a 2 hour expiration date.
function spu_createCookie(name, value, hours)
{
if (hours)
{
var date = new Date();
date.setTime(date.getTime()+(hours*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
{
var expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
Well -most obvious thing is to make "expire" date +2 hours ? :). Here You have nice prototype for that:
Adding hours to Javascript Date object?
Try this:
function writeCookie (key, value, hours) {
var date = new Date();
// Get milliseconds at current time plus number of hours*60 minutes*60 seconds* 1000 milliseconds
date.setTime(+ date + (hours * 3600000)); //60 * 60 * 1000
window.document.cookie = key + "=" + value + "; expires=" + date.toGMTString() + "; path=/";
return value;
};
Usage:
<script>
writeCookie ("myCookie", "12345", 24);
</script>
//for 24 hours
Try jquery-cookie. Makes it very easy to work with cookies.
The following one-liner will set a cookie, name, with the value, value, and an expiration of two hours from the time of its creation. If the optional argument, days, is supplied, the cookie will expire after that many days instead.
Warning: there is no error-checking, so if mandatory parameters are omitted when called, or arguments are mistyped, the function will throw an error.
spu_createCookie = (name, value, days) => { document.cookie = `${name}=${value}; expires=${new Date(Date.now() + (days ? 86400000 * days : 7200000)).toGMTString()}; path=/` }
Relevant JavaScript syntax concepts:
Arrow Functions
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
Template Literals
Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.
Ternary Operators
The conditional (ternary) operator is the only JavaScript operator that takes three operands ... This operator is frequently used as a shortcut for the if statement.
This would do it.
var now = new Date();
var time = now.getTime();
time += 7200 * 1000;
now.setTime(time);
document.cookie =
name+ '=' + value +
'; expires=' + now.toGMTString() +
'; path=/';

Categories

Resources