0

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)
{
?>

1 Answer 1

2

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.

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

1 Comment

Thanks for the response Eli. I am still learning php. Can you please show example with my code? thx.

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.