AdamH.us

Age Verification in PHP

by on Jan.26, 2012, under Web Design

I figured I’ve got this site, I might as well use it for something productive…

A few years ago, I wanted a way to tell the current age of a user for displaying on a PHP page. It took me a while to figure out as there wasn’t a guide or a pre-written function to do it for me that I could find. None that were light-weight enough for what I was doing, anyway…

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
< ?php
// Retrieving Age
// (c) AdamH.us
// $date in dd-mm-yyyy format
//
// Returns: int $age
function getAge($date) {
// Turn date string into array
$date = explode("-",$date);
// Compare Months
if ($date[1] == date("n")) {
// Compare dates
if ($date[0] >= date("j")) {
$age = date("Y")-$date[2];
} else {
$age = (date("Y")-$date[2])-1;
}
} elseif ($date[1] > date("n")) {
$age = date("Y")-$date[2];
} elseif ($date[1] < date("Y")) {
$age = (date("Y")-$date[2])-1;
}
return $age;
}
?>

You could also do a verification of age using this function:

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
< ?php
// Verify Age
// (c) AdamH.us
// $date in dd-mm-yyyy format
// $tAge - positive integer
// Can be used like: verifyAge($date,18)
//
// Returns: bool TRUE when age is equal or higher
// bool FALSE when age is lower
function verifyAge($date,$tAge) {
// Turn date string into array
$date = explode("-",$date);
// Compare Months
if ($date[1] == date("n")) {
// Compare dates
if ($date[0] >= date("j")) {
$age = date("Y")-$date[2];
} else {
$age = (date("Y")-$date[2])-1;
}
} elseif ($date[1] > date("n")) {
$age = date("Y")-$date[2];
} elseif ($date[1] < date("Y")) {
$age = (date("Y")-$date[2])-1;
}
return $age >= $tAge;
}
?>

Hopefully someone finds it useful. :)

© 2012, AdamH.us. All rights reserved. Please link back if you use it!

:, , ,

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!