Validating dates with PHP.

This is a tutorial on how to validate user-submitted dates using PHP. In certain cases, your users might have to select a date before submitting a web form. The date field could be for a hotel booking or the user could be selecting their date of birth. In this guide, I will show you how to validate this date and make sure that it is correct. If this validation is not carried out, a user could potentially enter a date that never occured.

Lets take a look at the following example:

//For example purposes, I am using an invalid date.
$date = "2016-02-31";

//Firstly, we need to "break" the date up by using the explode function.
$dateExploded = explode("-", $date);

//Our $dateExploded array should contain three elements.
if(count($dateExploded) != 3){
    throw new Exception('Invalid date format!');

//For the sake of clarity, lets assign our array elements to
//named variables (day, month, year).
$day = $dateExploded[2];
$month = $dateExploded[1];
$year = $dateExploded[0];

//Finally, use PHP's checkdate function to make sure
//that it is a valid date and that it actually occured.
if(!checkdate($month, $day, $year)){
    throw new Exception($date . ' is not a valid date!');

If you run the PHP code above, you’ll see that the final check results in an exception being thrown. Why? Because the 31st of February, 2016, never actually occurred (the month of February will only have 29 days at most).

A few points that are worth noting:

  • The format of the date field is extremely important. For example, if your form uses a DD/MM/YYYY format instead of YYYY-MM-DD, then you will obviously need to modify the explode operation (explode on “/” instead of “-“). You will also need to change how you reference each array element, as the day value will be stored at index 0 instead of 2.
  • PHP’s checkdate function is vital to date validation, as it takes leap years and the length of each month into consideration. If you fail to use the checkdate function, a user could potentially enter a date that will never occur.
  • You cannot rely on JavaScript or HTML5 datepickers for validation. Although these datepickers force the casual Internet user to select a correct, anyone with a basic knowledge of HTML can bypass this client-side validation using Firebug or Chrome Developer Tools. Therefore, server-side validation is required.