Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
511 views
in Technique[技术] by (71.8m points)

php - Validate if age is over 18 years old

Just wondering, can I do this to validate that a user has entered a date over 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');
    }
}

Just stumbled across this function date_diff: http://www.php.net/manual/en/function.date-diff.php Looks, even more promising.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why not? The only problem to me, is the User Interface - how you send out the error message elegantly to the user.

On another note, your function might not work properly as you did not intake a proper birthday (you are using a fixed birthday). You should change 'March 23, 1988' to $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'); 
    }
}

Or you can:

// 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...