只是想知道,我可以这样做来验证用户输入的日期是否超过 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');
}
}
刚刚偶然发现了这个函数 date_diff: http://www.php.net/manual/en/function.date-diff.php 看起来,更有前途。
最佳答案
为什么不呢?对我来说唯一的问题是用户界面——如何优雅地向用户发送错误消息。
另一方面,您的函数可能无法正常工作,因为您没有输入正确的生日(您使用的是固定生日)。您应该将“1988 年 3 月 23 日”更改为 $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');
}
}
或者你可以:
// 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;
}
关于php - 验证年龄是否超过 18 岁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1812589/