Validate if age is over 18 years old
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 validateAge($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 validateAge($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;
}
I think it is best using the DateTime class for this.
$bday = new DateTime("22-10-1993");
$bday->add(new DateInterval("P18Y")); //adds time interval of 18 years to bday
//compare the added years to the current date
if($bday < new DateTime()){
echo "over 18";
}else{
echo "below 18";
}
DateTime::diff can also be used to compare the date with the current date.
$today = new DateTime(date("Y-m-d"));
$bday = new DateTime("22-10-1993");
$interval = $today->diff($bday);
if(intval($interval->y) > 18){
echo "older than 18";
}else{
echo "younger than 18";
}
N/B: 1) for the second method , if $bday is greater than $today by 18 years or more, it will return older , so make sure date entered is less than $today . 2) DateTime works on php 5.2.0 and above
Here is a simplified extract from what I used for a banking system in Toronto, and this always worked perfectly, taking account of leap years of 366 days.
/* $dob is date of birth in format 1980-02-21 or 21 Feb 1980
* time() is current server unixtime
* We convert $dob into unixtime, add 18 years, and check it against server's
* current time to validate age of under 18
*/
if (time() < strtotime('+18 years', strtotime($dob))) {
echo 'Client is under 18 years of age.';
exit;
}
if( strtotime("1988/03/23") < (time() - (18 * 60 * 60 * 24 * 365))) {
print "yes";
} else {
print "no";
}
...not accounting for leaps years however