thednp
thednp

Reputation: 4479

Format GMT date to integer in PHP

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?

Upvotes: 0

Views: 266

Answers (1)

adeneo
adeneo

Reputation: 318272

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.

Upvotes: 2

Related Questions