什麼是最方便的方式,是使用PHP驗證表單的「最佳」方式?我不希望JavaScript這樣的語言驗證我的表單,我想知道使用PHP進行表單驗證的最佳方法,更乾淨的方法來完成它。使用PHP驗證表單的最佳方法
我是新來的PHP,我在註冊頁面上工作,我完成了它,我想知道我做的方法是否可以接受,以及是否有最佳,方便,乾淨的方法來驗證形成。
這是我使用的方法:
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>
服務器端驗證對於安全原因非常重要。你可以使用PHP框架。框架將以非常簡單的方式進行表單驗證。 –