Lumena
Lumena

Reputation: 1

How can I use getdate() to verify a user's age?

When a user attempts to register with my site, I need to verify that they are old enough. I am trying to do this using the getdate() function.

I understand what getdate() does, but I am struggling to understand how to use it correctly for this purpose.

<?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>";
}
?>

Upvotes: 0

Views: 90

Answers (2)

Don&#39;t Panic
Don&#39;t Panic

Reputation: 41820

If you correct this if ( $yob =$yob>= $date["year"]-16) to if ( $yob >= $date["year"]-16), then this will do what you're expecting it to and it will work some of the time. The problem is that depending on when someone's birthday is in the year compared to the current date, just subtracting the year like this will often give an incorrect result.

A better way would be to calculate the age using the DateTime::diff method. This should get you the person's exact age.

$age = date_create("$yob-$mob-$dob")->diff(new DateTime());

Then you can compare the year property of the resulting DateInterval object to verify the age.

if ( $age->y < 16) {
    echo "Too young to register!";
} elseif ($age->y > 117) {
    echo "Don't be silly, you are not that old!";
} else { ...

Upvotes: 0

Eihwaz
Eihwaz

Reputation: 1234

Try:

$registration = new DateTime(implode('-', array($yob, $mob, $dob)));
$now = new DateTime();

var_dump($now->diff($registration)->y);

This will give you the actual age, taking months, days and leap years into account.

DateTime Class Manual

Upvotes: 3

Related Questions