Skip to content

Instantly share code, notes, and snippets.

@EJTH
Last active August 29, 2015 14:01
Show Gist options
  • Save EJTH/e91797071fd7c2821832 to your computer and use it in GitHub Desktop.
Save EJTH/e91797071fd7c2821832 to your computer and use it in GitHub Desktop.
Simple and powerful function for date range validation in PHP using date() and eval() (So it is probably not 100% safe for user exposure, though input is sanitized somewhat). Syntax is simple and allows for every possible crazy date rules that might occour.
<?php
/**
* Validates a date to a specific rule. Rules has the following format:
* :[date-component]: ==|<|>|>=|<=|!= [number]
*
* So to validate if the date is the first of the month:
* :d: == 1
*
* And the first monday of the month:
* :w: == 1 && :d: <= 7
*
* On fridays and mondays:
* :d: == 1 || :d: == 5
*
* All variables used in date() can be used as a date-component.
*
* if rule is empty all dates are considered valid.
* @param type $rule
* @param type $date
* @return type
*/
function dateValid($rule,$date){
$DATE = (int) $date;
if(!$rule) return true;
/* Make it safe for eval by removing function calls and variable references */
$rule = preg_replace('/\w+\s*\(.*?\)|$/i','',$rule);
//replace rule notations
$f = create_function('$str', 'return "date(\'$str[1]\',\$DATE)";');
/*$f = function($str){
return "date('$str[1]',\$DATE)";
};*/
$rule = preg_replace_callback('/:(\w):/i', $f, $rule);
return @eval("return $rule;");
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment