background image

PHP 中 checkdate 日期验证方法详解

在 PHP 中如何检查一个日期是否有效呢,例如,你想要确保用户不会提交一个类似“1962 年 2 月
30 日”这样的生日。

很简单,我们可以使用 checkdate()函数,代码如下:

$valid = checkdate($month,$day,$year);

当$month 位于 1-12 之间,$year 位于 1-32767 之间,$day 位于 1 和$year 及$month 所代表
的相应年、月份中最大的天数之间时,函数 checkdate()会返回 true。checkdate()函数能够正确
地处理闰年,而且日期使用公历(阳历)来表示。

由于 checkdate()的有效年份太过宽泛,所以假如你要得到一个有效的出生日期的话,就必须要
对年份进行额外的验证。已经证实的人类的最长寿命是 122 岁。要验证出生日期所表示的年龄处在
18-122 岁之间,可以使用下例中所示的 pc_ checkbirthdate()函数。

<?php
functionpc_checkbirthdate($month,$day,$year) {
$min_age= 18;
$max_age= 122;
if(!checkdate($month,$day,$year)) {
returnfalse;
}
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)) {
returntrue;
}elseif(($year==$max_year) &&
(($month<$this_month) ||
(($month==$this_month) && ($day<=$this_day)))) {
returntrue;
}elseif(($year==$min_year) &&
(($month>$this_month) ||
(($month==$this_month&& ($day>$this_day))))) {
returntrue;
}else{
returnfalse;
}
}
// check December 3, 1974
if(pc_checkbirthdate(12,3,1974)) {
print"You may use this web site.";
}else{