Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$var is valid unix timestamp

I need a function to validate if the content of a variable is a valid unix timestamp.

I've checked this thread: Check whether the string is a unix timestamp but the problem is that the function in the most voted answer still can cause some errors, for eg:

function is_timestamp($timestamp)
{
   return ((string) (int) $timestamp === $timestamp)
   && ($timestamp <= PHP_INT_MAX)
   && ($timestamp >= ~PHP_INT_MAX);
}

// Some tests:
$timestamp = 1289216307;
var_dump(is_timestamp($timestamp));
var_dump(date('Y-m-d', $timestamp));

// result
bool(false)
string(10) "2010-11-08" 

$timestamp = '20101108';
var_dump(is_timestamp($timestamp));
var_dump(date('Y-m-d', $timestamp));

// result
bool(true)
string(10) "1970-08-21" 

Here, the first should be TRUE and the second should be FALSE so, what's the best way to test if a $var is a real valid unix timestamp?

like image 568
mjsilva Avatar asked Dec 16 '22 20:12

mjsilva


1 Answers

Here, the first should be TRUE and the second should be FALSE

Why? 20101108 is a valid UNIX timestamp, - as you say, it's August 21, 1970. Could well be a person's birthday for example.

The only way to achieve what you want is to set a range of dates that mark a "sane" timestamp by the definition you are working with - e.g. anything after January 1st, 2000 - and do a check against that.

like image 84
Pekka Avatar answered Dec 31 '22 01:12

Pekka