Example 3-1. pc_checkbirthdate( )
function pc_checkbirthdate($month,$day,$year) {
$min_age = 18;
$max_age = 122;
if (! checkdate($month,$day,$year)) {
return false;
}
list($this_year,$this_month,$this_day) = explode(',',date('Y,m,d'));
$min_year = $this_year - $max_age;
$max_year = $this_year - $min_age;
print "$min_year,$max_year,$month,$day,$year\n";
if (($year > $min_year) && ($year < $max_year)) {
return true;
} elseif (($year == $max_year) &&
(($month < $this_month) ||
(($month == $this_month) && ($day <= $this_day)))) {
return true;
} elseif (($year == $min_year) &&
(($month > $this_month) ||
(($month == $this_month && ($day > $this_day))))) {
return true;
} else {
return false;
}
}
Here is some sample usage:
// check December 3, 1974
if (pc_checkbirthdate(12,3,1974)) {
print "You may use this web site.";
} else {
print "You are too young to proceed.";
exit( );
}
This function first uses checkdate( ) to make sure
that $month, $day, and
$year represent a valid date. Various comparisons
then make sure that the supplied date is in the range set by
$min_age and $max_age.
If $year is noninclusively between
$min_year and $max_year, the
date is definitely within the range, and the function returns
true. If not, some additional checks are required.
If $year equals $max_year
(e.g., in 2002, $year is 1984),
$month must be before the current month. If
$month equals the current month,
$day must be before or equal to the current day.
If $year equals $min_year
(e.g., in 2002, $year is 1880),
$month must be after the current month. If
$month equals the current month,
$day must be after the current day. If none of
these conditions are met, the supplied date is outside the
appropriate range, and the function returns false.
The function returns true if the supplied date is
exactly $min_age years before the current date,
but false if the supplied date is exactly
$max_age years after the current date. That is, it
would let you through on your 18th birthday, but not on your 123rd.