What is the the most convenient way, the "best" way for validate a form with PHP? I don't want languages like Javascript for validate my form, I want to know the best approach for do a form validation using only PHP, the more cleanly way to do it.
I'm new with PHP, I'm working on a registration page, I finish it and I want to know if the approach that I do it's acceptable and if there is a best, convenient, clean way for validate a form.
This is the approach that I use:
if (post form submitted (action same page)) {
$errors = array(); // Initialize the variable error as an array
if (various controls for the username which must not occur) {
$errors[] = 'Inputnot valid.';
}
// for example:
if (empty($_POST['username']) || !ctype_alnum($_POST['username'])) {
$errors[] = 'Username not valid.';
}
if (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Email not valid.';
}
if (empty($errors)) { // Check if the array is empty so that there are no errors
echo 'everything is ok';
} else { // There is errors
foreach ($errors as $error) {
echo $error;
}
}
}
// Begin HTML
<!DOCTYPE html>