tags:

views:

211

answers:

2

Just wondering, can I do this to validate that a user has entered a date over 18?

//Validate for users over 18 only
function time($then, $min)
{
$then = strtotime('March 23, 1988');
//The age to be over, over +18
$min = strtotime('+18 years', $then);
echo $min;
if(time() < $min) 
{
die('Not 18'); 
}
}

Just stumbled across this function date_diff: http://www.php.net/manual/en/function.date-diff.php Looks, even more promising.

+2  A: 

Why not? The only problem to me, is the User Interface - how you send out the error message elegantly to the user.

On another note, your function might not work properly as you did not intake a proper birthday (you are using a fixed birthday). You should change 'March 23, 1988' to $then

//Validate for users over 18 only
function time($then, $min)
{
  // $then will first be a string-date
  $then = strtotime($then);
  //The age to be over, over +18
  $min = strtotime('+18 years', $then);
  echo $min;
  if(time() < $min) 
  {
    die('Not 18'); 
  }
}

Or you can:

// validate birthday
function validate_age($birthday, $age = 18)
{

  // $birthday can be UNIX_TIMESTAMP or just a string-date.
  if(is_string($birthday)){
    $birthday = strtotime($birthday);
  }

  // check
  // 31536000 is the number of seconds in a 365 days year.
  if(time() - $birthday < $age * 31536000) 
  {
    return false;
  }

  return true;

}
thephpdeveloper
I was just doing that mr. editor. :P
William
haha guess I was faster then? my bad.
thephpdeveloper
Also, remember that a year is technically 365.242199 days in a year. So you should be multiplying by 31556926 instead of 31536000. Also, Google is really nice about these kinds of calculations, just ask Google "1 years in seconds" :)
William
The above comment is talking about with leap year added on obviously. Maybe make a boolean option in your method to enable / disable that option?
William
That's really neat, I was just going to spend a couple of hours wading through like a million different ways to validate an agefrom here: http://www.php.net, thank you. The comments are superb, again thank you.
Newb
Just realized you can rank comments, leet.
Newb
Keep in mind that age should be calculated using string comparissons and not using math, however you can get pretty close using math.
Alix Axel
+1  A: 
if( strtotime("1988/03/23") < (time() - (18 * 60 * 60 * 24 * 365))) {
  print "yes";
} else {
  print "no";
}

...not accounting for leaps years however

mtvee
That's amazing so many ways to achieve the same objective.
Newb