Age Validation Function [PHP]

The most recent college project I’ve had is to develop a system for a video games shop. The last task was to evaluate the system then recommend and implement any improvements.

One idea I had was for validating whether a customer stored in the database is in fact old enough to be purchasing the games in their order, so I wrote a little PHP function to do just that.

<?php
	// Function to calculate whether customer is old enough to purchase product – DOB input in format YYYY-MM-DD
	// Created by Jacob Ward (http://www.jacobward.co.uk) - Please leave this in if you choose to use this in your projects.

	function validate_age($dob, $restriction) {
	
		$dates = explode("-", $dob);	// Exploding sections of date into array
		
		$year = date("Y") - $dates["0"];	// Subtracting entered year from current year
		$month = date("m") - $dates["1"];	// Subtracting entered month from current month
		$day = date("d") - $dates["2"];	// Subtracting entered day from current day
		
		// If month is negative, means it's a year earlier - Decrement year by 1. Else if month is 0 and day is negative, means it's a year earlier - Decrement year by 1
		if ($month < 0) {
			$year--;
		} elseif ($month == 0 && $day < 0) {
			$year--;
		}
		
		// If customer's age is greater than or equal to certificate then age is valid, else it's invalid
		if ($year >= $restriction) {	
			$valid_age = TRUE;
		} else {
			$valid_age = FALSE;
		}
		
		return $valid_age;	// Return TRUE or FALSE whether customer is old enough to purchase product
	}
?>

It should be pretty simple to understand, but I’ll talk it through.

The function takes two, a date of birth (in the format of YYYY-MM-DD) and the age restriction, e.g.

$dob = "1985-11-18";
$age_restriction = 18;

validate_age($dob, $age_restriction);

It then returns TRUE if the validation is successful or FALSE if it is unsuccessful.

And that’s it! Hope it comes in handy at some point.

Leave a Reply