当用户试图注册我的网站时,我需要验证它们是否足够旧。我正在尝试使用getdate()
函数来完成此操作。
我理解getdate()
的作用,但我很难理解如何正确使用它。
<?php
$fn = $_POST["fullname"];
$un = $_POST["username"];
$pw = $_POST["password"];
$dob = $_POST["dayofbirth"];
$mob = $_POST["monthofbirth"];
$yob = $_POST["yearofbirth"];
$date = getdate();
if ( $yob =$yob>= $date["year"]-16)
{
echo "Too young to register!";
}
elseif ($yob <=1899)
{
echo "Don't be silly, you are not that old!";
}
else
{
echo "<h1>Thank you for registering with us!</h1>";
echo "<p> You have successfully registered with these details:
<br>Your full name :$fn<br> Username: $un
<br>Date of birth: $dob $mob $yob</p>";
}
?>
尝试:
$registration = new DateTime(implode('-', array($yob, $mob, $dob)));
$now = new DateTime();
var_dump($now->diff($registration)->y);
这将给出你的实际年龄,将月、日和闰年考虑在内。
DateTime类手动
如果您将此if ( $yob =$yob>= $date["year"]-16)
更正为if ( $yob >= $date["year"]-16)
,则这将达到您的预期效果,并且在某些时间内会起作用。问题是,根据某人的生日与当前日期相比是在一年中的什么时候,像这样减去年份往往会得出错误的结果。
更好的方法是使用DateTime::diff方法计算年龄。这应该能让你知道这个人的确切年龄。
$age = date_create("$yob-$mob-$dob")->diff(new DateTime());
然后,您可以比较生成的DateInterval对象的year属性来验证年龄。
if ( $age->y < 16) {
echo "Too young to register!";
} elseif ($age->y > 117) {
echo "Don't be silly, you are not that old!";
} else { ...