How to create a central PHP input validation file and use it?
I have some basic validation of some variables, but it is repeated on more than one page, how can I create a validation file and call it when needed? Here is some code:
$rep = '';
$clean_rep = '';
$rep = $_GET[rep];
//Basic Variable Validation
switch ($rep){
ca开发者_JAVA技巧se 'All':
case 'Ian':
case 'Mike':
case 'Stan':
case 'Gena':
$clean_rep = $rep;
break;
}
If I put this in a separate file and included it on the needed pages, I assume it would have to be in a function so it can be singled out:
validation.php:
function validateRep($rep){
switch ($rep){
case 'All':
case 'Ian':
case 'Mike':
case 'Stan':
case 'Gena':
$return("Clean");
break;
}
}
once the variable is returned as "Clean", do I just assign $rep in the first script to $clean_rep? or is there a better procedure to doing this?
validation.php:
function validateRep($rep){
return in_array($rep, array(
'All', 'Ian', 'Mike', 'Stan', 'Gena',
));
}
[in_array][1]
would check if first parameter exists in the second array parameter, and return true if it exists, false if it's not, and the validateRep
function would return the returned value in turn. so when calling, you'll get true if it's valid, false if it's not.
You can do it like this:
function validateRep($rep)
{
switch ($rep)
{
case 'All':
case 'Ian':
case 'Mike':
case 'Stan':
case 'Gena':
$return($rep);
break;
}
return null;
}
And in your main code files:
$rep = validateRep($rep);
精彩评论