php - 验证年龄是否超过 18 岁

标签 php

只是想知道,我可以这样做来验证用户输入的日期是否超过 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/

相关文章:

PHPMailer SMTP 本地主机,证书错误

php - 为什么文件存在时 file_exists() 返回 false?

php - 如何使用 PHP 构建动态 MySQL INSERT 语句

php - 安装 GD Toolkit 时出错

php - 防止通过 API 在 MySQL 中进行多次 INSERT

php - 从 MySQL 结果构建 HREF

php - 无法从 laravel eloquent 中的连接查询的第二个表中获取数据

PHP Mysql 选择多个表不同的行名

php - 外键约束错误失败

php - 异步聊天