I have a PHP calendar that generates a calendar based on the month and year. I use $_GET["year"]. So, it appears in the URL of the page. Therefore, the user can input any year. How can I verify that the year they entered is a year (like 2010) and not a random input (like 2t8e7sjj2)?
I figured out how to verify month like this:
$m = $_GET["mo开发者_如何学运维nth"];
if($m!=1 && $m!=2 && $m!=3 && $m!=4 && $m!=5 && $m!=6 && $m!=7 && $m!=8 && $m!=9 && $m!=10 && $m!=11 && $m!=12)
{
$m = date("m");
}
But I can't do this with year (since the year could be any number). Also, is there a better way to verify the month other than above?
Thanks.
try http://php.net/manual/en/function.checkdate.php
if (checkdate($_GET['month'], 1, $_GET['year'])) ... okay
What are your restrictions on year other than it must be a positive integer number?
Regarding your month validation (and most probably your year one as well), you should be checking against a numeric range, eg
$m = ctype_digit($_GET['month']) ? (int) $_GET['month'] : 0;
if ($m >= 1 && $m <= 12) {
// month is valid
}
Yes, you can verify the month like this:
$month = intval($_GET['month']);
if ($month >= 1 && $month <= 12) {
// ...
}
You don't even need to verify the year; just clean it with intval()
http://php.net/intval
if (is_numeric($_GET['year']) && in_array($_GET['year'], range(1900,2100)))
also
if (is_numeric($_GET['month']) && in_array($_GET['month'], range(1,12)))
I'd do something like:
$m = intval($_GET['month']);
$y = intval($_GET['year']);
if($m < 1 || $m > 12 || $y < 1900 || $y > 2100) echo "bad input!";
2 things.
1st: you can use the pasre_url() method in php to ensure that there is no invalid formatting.
2nd: to match a year/month (since a year must be 4 numeric digits) they can be verified easily using regular expressions. Since I don't like to take credit for the sources I learned something ... look here to validate dates.
http://www.regular-expressions.info/dates.html
If you need I can write the .php for you, but it should be pretty easy from this point.
You can use this to check both ( month , year )
<?
// define vars
$months = array();
$years = array();
// create new array with months values
for($i=1;$i<=12;$i++)
array_push($months,$i);
// create new array with years values ex: begin with year 1930 to 2011
for($i=1930;$i<=2011;$i++)
array_push($years,$i);
// Check Values
if(in_array($_GET['m'],$months))
{ $m = $_GET['m']; }
else
{ $m = date("m"); }
if(in_array($_GET['y'],$years))
{ $y = $_GET['y']; }
else
{ $y = date("Y"); }
?>
精彩评论