How to Validate Age With PHP

Sunday, May 3rd, 2009

I was recently browsing the analytic statistics and information for Dev-Tips when I noticed that a common search was appearing on the site. The search terms were how to validate age with php. I immediately saw this as an opportunity to provide an answer to a very simple php question, as it is quite simple to validate an age with php. Let's have a quick look and write a script that will allow us to validate that a user is a certain age with php.

First, let me say that there are a lot of different ways that we could do this, we could spend weeks writing different ways on how to accomplish this best. Disclaimer aside, let's look at a simple and procedural option.

<?php
//users birthday, ideally you would take this data from a form
$user_bd = strtotime('March 14, 1997');

//Age requirement, using 21 as the minimum age required
$age_req = strtotime('+21 years', $user_bd);

//Grab the current UNIX timestamp and compare it to the minimum required
if(time() < $age_req){
	echo 'Not 21 years or older.';
}
else{
	echo 'Word. Come on in.';
}
?>

Our script goes through the following steps:

  1. Parse the users birthday as a UNIX timestamp using strtotime() and store the result in a variable. Ideally this info would come from a form/select box on your page.
  2. Determine the minimum age they need to be. We will use 21 years old. We add 21 years to our original date, parse it as a UNIX timestamp, and store it in a variable.
  3. If the current timestamp is less than the age required, print to the screen or do whatever you wish with the user (re-direct, exit() etc.). Else, the user is old enough.

And that is one way you can validate any age with php. Hopefully, the users coming to this site will now find it more helpful that we have posted the answer to the common search query. Happy coding!


If you enjoyed this article, you might consider subscribing to our rss feed to stay updated with all the latest tips and articles!

ABOUT THIS AUTHOR

Hi, I'm Drew Douglass and I make sure Dev-Tips.com runs smoothly. I also work for Envato Support and write for NETTUTS.com and ThemeForest.net. I'm passionate about anything web development related, especially php, WordPress, MySQL, and jQuery. Feel free to follow me on twitter.
  1. May 3, 2009 at 1:34 pm
    • May 3, 2009 at 2:12 pm
  2. May 3, 2009 at 2:15 pm
    • May 3, 2009 at 2:18 pm
  3. May 3, 2009 at 3:35 pm
    • May 3, 2009 at 4:06 pm
  4. May 4, 2009 at 8:36 am
  5. May 9, 2009 at 10:01 pm

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Popular Series

Output Buffering Articles
Build a Custom AJAX and PHP Contact Form
The Ultimate Image Gallery Manager.
ThemeForest Premium Site and WordPress Templates