正在 PHP 验证年龄

Verifying age on PHP

我看了这里的很多帖子,还是想不通。

我正在尝试验证某人在注册我的网站之前是否超过 13 岁。这是我目前所拥有的

<?php
if (is_string($_POST['birthday']) && $_POST['birthday'] != 'mm/dd/yyyy')
{
    $dateObj = new DateTime($_POST['birthday']);
    $ageLimit = new DateTime('13 years');
    $now = new DateTime(date("Y/m/d"));
    $checkDate = $now->diff($ageLimit);;
    if($checkDate > $dateObj)
    {
        $errors[]='You must be atleast 13 years old to join.';
    }
    else
    {
        $bday = mysqli_real_escape_string($db,$_POST['birthday']);
    }
}
else
{
    $errors[]= 'Enter your birthday.';
}

代码将始终运行

$bday = mysqli_real_escape_string($db,$_POST['birthday']);}

无论在日期字段中输入什么,结果始终为 1。

谁能帮我解决这个问题?我无法自己解决这个问题。

<b>Birth Date</b><br><input type="date" name="birthday"
value=<?php if(isset($_POST['birthday']))echo $_POST['birthday'];?>><br>

比较运算符与 DateTime 一起使用,请参阅答案 here。 所以像这样的东西应该可以工作

$dateObj=new DateTime($_POST['birthday']);
$ageLimit=new DateTime('-13 years');
if($dateObj > $ageLimit){
   //TOO YOUNG
}

根据评论编辑

替换 if(isset($_POST['birthday']))echo $_POST['birthday'];

if(isset($_POST['birthday'])) { 
  echo $_POST['birthday']; 
} else { 
  echo 'mm/dd/yyyy';
}

或更改

if (is_string($_POST['birthday']) && $_POST['birthday'] != 'mm/dd/yyyy')

  if (!empty($_POST['birthday']) && is_string($_POST['birthday']))

你有几个错误

  1. “13 年”不是 DateTime()
  2. 的有效值
  3. 'Y/m/d' 格式的日期不是 DateTime()
  4. 的有效格式
  5. $checkDate 是一个 DateInterval 对象,不能与 DateTime 对象相比较

您可以通过比较 DateTime 个具有可比性的对象来解决此问题并简化您的代码:

$birthday = new DateTime($_POST['birthday']);
$ageLimit = new DateTime('-13 years');
if ($birthday < $ageLimit) {
    // they're old enough
}
else {
     // too young
} 

Demo

使用 strtotime 计算日期差异可能更容易。数字越大越年轻。因此,如果该人的年龄高于最低年龄,则他们还不够大。

if(is_string($_POST['birthday'])&&$_POST['birthday']!='mm/dd/yyyy') {
   $minAge = strtotime("-13 years");
   $dateObject = strtotime($_POST['birthday']);

   if($dateObject > $minAge) {
      $errors[]= 'You must be atleast 13 years old to join.';
   }

} else {
    $errors[]='Enter your birthday.';
}