Reputation: 20
I am using the below script for validation. I want to know if there is a way to convert this script to show all errors at once instead of one at a time? Also, is there anything more I can do to prevent header injection?
thanks.
<?php
session_start();
/* Check all form inputs */
$fname = check_input($_POST['fname'], "Friend's Name cannot be empty.");
$femail = check_input($_POST['femail'], "Friend's email cannot be empty.");
$yname = check_input($_POST['yname'], "Your Name cannot be empty.");
$yemail = check_input($_POST['yemail'], "Your email cannot be empty.");
$subject = check_input($_POST['subject'], "Subject cannot be empty.");
$comments = check_input($_POST['comments'], "Comments cannot be empty.");
/* alphabet only */
if(!preg_match("/^([A-Za-z\s\-]{2,45})$/i", $fname))
{
show_error("Friend's name is not valid.");
}
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $femail))
{
show_error("Your friend's email address is not valid.");
}
if(!preg_match("/^([A-Za-z\s\-]{2,45})$/i", $yname))
{
show_error("Your name is not valid.");
}
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $yemail))
{
show_error("Your email address is not valid.");
}
htmlentities ($message, ENT_QUOTES);
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlentities($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
Upvotes: 0
Views: 120
Reputation: 1024
Something I often do is use an $errors array. So you would define an empty array before all your checks, and then inside of each check for show_error you would add that string to your errors array:
$errors[] = "Friend's name is not valid.";
Then at the end, check to see if the error array is empty. If it is, then nothing failed. Otherwise, you now have an array of all the errors that you can display however you'd like.
Upvotes: 2