checking the date with php
Thursday, March 23rd, 2006bits of the code here are taken from php.net
to check the date in php you can use a function called checkdate() but to get it working in a clever way with a form use the function below
< ?php
/**
* Checks for a valid date
*
* @param string Date in the format given by the format parameter.
* @param integer Disallow years more than $yearepsilon from now (in future as well as in past)
* @param string Formatting string. Has to be one of 'dmy', 'dym', 'mdy', 'myd', 'ydm' or 'ymd'. (Default is 'ymd' for ISO 8601 compability)
* @return array [ year, month, day ]
* @since 1.0
*/function datecheck($date, $yearepsilon=200, $format='dmy') {
$date=str_replace("/", "-", $date);
$format = strtolower($format);
if (count($datebits=explode('-',$date))!=3) return false;
$year = intval($datebits[strpos($format, 'y')]);
$month = intval($datebits[strpos($format, 'm')]);
$day = intval($datebits[strpos($format, 'd')]);if ((abs($year-date('Y'))>$yearepsilon) || // year outside given range
($month<1) || ($month>12) || ($day<1) ||
(($month==2) && ($day>28+(!($year%4))-(!($year%100))+(!($year%400)))) ||
($day>30+(($month>7)^($month&1)))) return false; // date out of rangereturn checkdate($month,$day,$year );
}?>
this will check the variable $date.
First of all it replaces any ‘/’ symbols with ‘-’.
Using the specified format ($format) it checks to see you have 3 bits (day ,month, year).
Using the range of dates ($yearepsilon) it checks that the date is in range.
Then php’s checkdate function is used - this checks to see whether that date actuall did, or could exist.Only if everything matches will the function return true - otherwise it will return false
The checkdate function is pretty smart - it knows every day of every year between 1 and 32767 inclusive. For instance if 29/2/2000 were entered (using the day, month, year format) checkdate would return true as 2000 was a leapyear.
Using the function:
If you had a field with the name ‘date’ in your form you could set an error variable if the date was invalid, then use that error variable tell the user they’d made a mistake.
< ?php
if (datecheck($_POST['date']) == false){
$error = 1;
}
else { echo "the date is fine";}?>

