3.8. Validating a Date
Problem
You want to check if a date is valid. For example, you want to make sure a user hasn’t provided a birthdate such as February 30, 1962.
Solution
Use checkdate( )
:
$valid = checkdate($month,$day,$year);
Discussion
The function checkdate( )
returns true
if $month
is
between 1 and 12, $year
is between 1 and 32767,
and $day
is between 1 and the correct maximum
number of days for $month
and
$year
. Leap years are correctly handled by
checkdate( )
, and dates are rendered using the
Gregorian calendar.
Because checkdate( )
has such a broad range of
valid years, you should do additional validation on user input if,
for example, you’re expecting a valid birthdate.
The Guinness Book of World Records says the
oldest person ever reached 122. To check that a birthdate indicates a
user between 18 and 122 years old, use the
pc_checkbirthdate( )
function shown in Example 3-1.
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) ...
Get PHP Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.