Reputation: 137
I have a ton of form fields (34 at last count)spread across the site so I am writing a catch as many things as possible function to do the bulk validation, then I will take care of the less common items on a perform basis.
On certain $_POST
keys I need to check if the value is alphanumeric.
For example $_POST['username']
needs to be checked. $_POST['firstname']
doesn't need to be checked as it can only be letters (we will check for that later).
I was going to do something like the following but it seems like I am creating to much overhead by skippng so many and to only check 5 or 6 values.
foreach($_POST as $key => $value){
if($key == 'descr'){ continue; }
if($key == 'imageUploads'){ continue; }
// etc
// etc
// etc
if(!ctype_alnum($value)){
$notAlNum[] = $key.' is not alphnumeric;
}
}
Is there another way I could do this without the overhead of looping through the whole post array?
Pieced together from answer this is the solution I came up with, it is ugly but it works.
if(in_array($_POST['userName'] || $_POST['pswd'] || $_POST['oldpswd'] || $_POST['activationCode'],$_POST)){
$toCheck = array($_POST['userName'],$_POST['pswd'],$_POST['oldpswd'],$_POST['activationCode']);
foreach($toCheck as $key => $var) {
if(empty($var)){ continue; }
if(!ctype_alnum($var)){
$errormsg[] = $var.' is not alphnumeric';
}
}
}
Upvotes: 1
Views: 72
Reputation: 99
You could use PHP's filter_input functionality, instead of accessing $_POST directly. This allows you to sanitize and validate the contents of the array (e.g. whether or not it's alphanumeric), and is generally regarded as more secure than accessing the array directly. For example:
$user = filter_input(INPUT_POST, 'user', FILTER_VALIDATE_REGEXP, ['options' => [
'regexp' => '/[a-z_\-0-9]/i']
]);
This does mean following a slightly different pattern to what you described above though - now you'd be doing your validation at the point when you get hold of each POST variable. You'd just need to decide for each variable how you want to santitize/filter it.
Upvotes: 1
Reputation: 1202
Why not create an array of keys to check? e.g.
foreach([ 'username' => true, 'otherField' => false ] as $field => $required) {
if ((!isset($_POST[$field]) || strlen($_POST[$field])) == 0 && !$required) continue;
if (!isset($_POST[$field]) || strlen($_POST[$field]) == 0) {
$errors[] = "$field is required";
}
else if (!ctyle_alnum($_POST[$field])) {
$errors[] = "$field is not alphanumeric";
}
}
Then you're not wasting time processing extraneous data
Upvotes: 0
Reputation: 9508
To just check those few variables
$toCheck = array('firstVar2Check','secondVar2Check',...);
foreach($toCheck as $var) {
if(!ctype_alnum($_POST[$var])){
$notAlNum[] = $var.' is not alphnumeric';
}
}
Upvotes: 2