1

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";
    }
}
4
  • you could use 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 found Commented May 24, 2018 at 19:29
  • What exactly do you mean by error numbers? Could you elaborate? Commented May 24, 2018 at 19:36
  • for example, if($formErrors !== true) { exit('9');}. this will interrupt the script and return the string '9' which you can check for using your frontend Commented May 24, 2018 at 19:36
  • Do I then use these numbers to display errors accordingly or are they for something else? Because my functions throw errors in an array which I can then display with $formErrors['error']; Commented May 24, 2018 at 19:39

1 Answer 1

1

You could indeed chain the if's together using elseif. I would however suggest some changes to the functions. Instead of letting them validate and return an array containing some errors, you'd need to only let them validate and return either true or false

It would look somewhat like this:

function validateLength($stringToValidate, $minimumLength) {
    if(strlen($stringToValidate) < $minimumLength) {
        return false;
    } else {
        return true;
    }
}

function validateEmail($emailToVerify) {
    if(filter_var($emailToVerify, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}

function formIsFilledIn(array $formInputs = []) {
    foreach ($formInputs as $inputField) {
        if(empty($inputField)) {
            return false;
        }
    }
    return true;
}

This means that you can do the following:

if(!formIsFilledIn($_POST)) {
    $error = [
        'error' => '<strong>Error: </strong> Fill in all fields.',
        'class' => 'alert alert-danger',
    ];

} elseif(!validateLength($_POST['username'], 8) || !validateLength($_POST['password'], 8)) {
    $error = [
        'error' => 'Minimum length is 8 charachters',
        'class' => 'alert alert-danger',
    ];
}

elseif(!validateEmail($_POST['email'])) {
    $error = [
        'error' => '<strong>Error:</strong> That is not a valid email address',
        'class' => 'alert alert-danger'
    ];
}

else {
// now you can call a function that starts to insert stuff, everything has been validated
}

Of course, this would becomes longer the longer the form will get. An other option would be to iterate over the post and check if all fields have a valid length. When that is done you can check the email and all other special fields

Sign up to request clarification or add additional context in comments.

2 Comments

So I could then echo this error message somewhere else on my page using echo $error['error']; I see and understand what you did here, but this is what I was trying to prevent originally. I want to do centralised error handling, so I only have to change it in one place if I need to change anything in the future. What are the advantages of doing it this way and is there / are there alternatives?
An advantage of this way is that the functions do exactly what they say they do, validate and nothing else. That means that you can use the functions at other places. It also means you have a single place, or function(if you'd put the validating part in a function) where you have to change error messages. Last but not least if the first if fails, the other ifs and the else will not get executed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.