I've created a registering form, and I'd like to validate user input, for security purposes.
I've created some functions, shown below.
I am just unsure on how to implement them correctly. Do I nest if statements? Do I just keep it like I have it now?
How do I stop my script when something isn't right? To prevent an insert from even being tried when something isn't right.
Any help is greatly appreciated.
function validateLength($stringToValidate, $minimumLength) {
if(strlen($stringToValidate) < $minimumLength) {
return [
'error' => 'Minimum length is 8 charachters',
'class' => 'alert alert-danger',
];
} else {
return true;
}
}
function validateEmail($emailToVerify) {
if(filter_var($emailToVerify, FILTER_VALIDATE_EMAIL)) {
return true
} else {
return [
'error' => '<strong>Error:</strong> That is not a valid email address',
'class' => 'alert alert-danger'
];
}
}
function formIsFilledIn(array $formInputs = []) {
foreach ($formInput as $inputField) {
if(empty($inputField)) {
return [
'error' => '<strong>Error: </strong> Fill in all fields.',
'class' => 'alert alert-danger',
];
}
}
return null;
}
Now, I'm using every function like so.
$formErrors = formIsFilledIn($_POST);
if($formErrors !== null) {
// Something is not filled in
}
$formErrors = validateLength($_POST['username'], 8);
if($formErrors !== true) {
// Username doesn't have enough characters
}
$formErrors = validateLength($_POST['password'], 8);
if($formErrors !== true) {
// Password doesn't have enough characters
}
For completeness, this is the insert part (it works properly)
$stmt = $connect->prepare('INSERT INTO `users` (user_name, user_password, user_email, user_perms, user_created_at) VALUES (?, ?, ?, ?, ?)');
if($stmt) {
$username = $_POST['username'];
$password = hashPassword($_POST['password']);
$email = $_POST['email'];
$date = date('Y-m-d H:i:s');
$perms = "Gebruiker";
$stmt->bind_param('sssss', $username, $password, $email, $perms, $date);
if($stmt->execute()) {
$err = "<strong>Success: </strong> The account has been created";
$class = "alert alert-success";
} else {
$err = "<strong>Error:</strong> Something went wrong";
$class = "alert alert-danger";
}
}
exit()and define error numbers related to each case; similar to the way web browsers return a 404 error if the page can't be foundif($formErrors !== true) { exit('9');}. this will interrupt the script and return the string '9' which you can check for using your frontend$formErrors['error'];