php 验证年龄是否超过18岁

xxb16uws  于 2023-02-03  发布在  PHP
关注(0)|答案(7)|浏览(162)

只是想知道,我可以这样做来验证用户输入的日期超过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看起来,更有希望。

ekqde3dh

ekqde3dh1#

为什么不呢?对我来说唯一的问题,是用户界面-你如何优雅地向用户发送错误信息。
另一方面,由于您没有输入正确的生日(您使用的是固定生日),函数可能无法正常工作。您应该将“March 23,1988”更改为$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;
}
4uqofj5v

4uqofj5v2#

这是我在多伦多的银行系统中使用的一个简化的摘录,它总是完美地工作,考虑到闰年的366天。

/* $dob is date of birth in format 1980-02-21 or 21 Feb 1980
 * time() is current server unixtime
 * We convert $dob into unixtime, add 18 years, and check it against server's
 * current time to validate age of under 18
 */

if (time() < strtotime('+18 years', strtotime($dob))) {
   echo 'Client is under 18 years of age.';
   exit;
}
mxg2im7a

mxg2im7a3#

我认为最好使用DateTime类来实现这一点。

$bday = new DateTime("22-10-1993");  
$bday->add(new DateInterval("P18Y")); //adds time interval of 18 years to bday  
//compare the added years to the current date  
if($bday < new DateTime()){   
    echo "over 18";  
}else{  
    echo "below 18";
}

DateTime::diff还可以用于比较日期和当前日期。

$today = new DateTime(date("Y-m-d"));
$bday = new DateTime("22-10-1993");
$interval = $today->diff($bday);
if(intval($interval->y) > 18){
    echo "older than 18";
}else{
    echo "younger than 18";
}

B:1)对于第二种方法,如果$bday比$today大18年或更多,则返回更早的日期,因此请确保输入的日期小于$today。2)DateTime适用于php 5.2.0及更高版本

goucqfw6

goucqfw64#

if( strtotime("1988/03/23") < (time() - (18 * 60 * 60 * 24 * 365))) {
  print "yes";
} else {
  print "no";
}

......但是,不考虑闰年

ttygqcqt

ttygqcqt5#

HTML输入:

<input type="date" class="form-control" placeholder="Data of Birth" name="dateOfBirth">

PHP代码:

function validateDateOfBirth($birthDay)
    {
// convert user input date to string and +18 years;
// compare user input date with current date;

        if (time() < strtotime('+18 years', strtotime($birthDay))) {
            return 'Not 18';
        }
        return "user is older than 18 years old";
    }
dohp0rv5

dohp0rv56#

<?php
 $dob = $_POST['dob'] ?? ''; 
 $message = '';

 # Validate Date of Birth
 if (empty($dob)){
  # the user's date of birth cannot be a null string
  $message = 'Please submit your date of birth.';
 }
 elseif (!preg_match('~^([0-9]{2})/([0-9]{2})/([0-9]{4})$~', $dob, $parts)){
  # Check the format
  $message = 'The date of birth is not a valid date in the format MM/DD/YYYY';
 }
 elseif (!checkdate($parts[1],$parts[2],$parts[3])){
  $message = 'The date of birth is invalid. Please check that the month is between 1 and 12, and the day is valid for that month.';
 }
 
 if ($message == '') {
  # Convert date of birth to DateTime object
  $dob =  new DateTime($dob);

  $minInterval = DateInterval::createFromDateString('18 years');
  $maxInterval = DateInterval::createFromDateString('120 years');
 
  $minDobLimit = ( new DateTime() )->sub($minInterval);
  $maxDobLimit = ( new DateTime() )->sub($maxInterval);
 
  if ($dob <= $maxDobLimit)
   # Make sure that the user has a reasonable birth year
   $message = 'You must be alive to use this service.';
   # Check whether the user is 18 years old.
  elseif ($dob >= $minDobLimit) {
   $message = 'You must be 18 years of age to use this service.';
  }
 
  if ($message == '') {
   $today = new DateTime();
   $diff = $today->diff($dob);
   $message = $diff->format('You are %Y years, %m months and %d days old.');
  }
 }
?>
----------------------------------
<p><b><?=$message?></b></p>
<form method="post" action="">
Your date of birth: <br>
<input type="text" name="dob" id="dob" placeholder="MM/DD/YYYY"><br>
<input type="submit" name="Submit" value="submit">
</form>
f4t66c6m

f4t66c6m7#

php文件

if (isset($_POST['bdate'])){
    $bdate = $_POST['bdate'];
    $age = (date("Y-m-d") - $bdate);


}  //if age if 17 or younger error msg
if ($age < 17) {
    echo "Must 18 or older.";
}
else{ //if age is 120 or greather error msg
    if ($age > 120) {
        echo "Real age please.";
    }
    else{
        echo "$age";
    }
}

HTML代码:

<form action="" method="POST"> 

    <p><label>Birth Date &nbsp;&nbsp;: </label>
    <input id="bdate" type="date" name="bdate" required placeholder="" /></p>
    <input class="btn register" type="submit" name="submit" value="Register" />
</form>

相关问题