我使用下面的脚本进行验证。我想知道是否有一种方法来转换这个脚本,一次显示所有的错误,而不是一次一个?此外,还有什么我可以做,以防止头部注入?
谢谢。
<?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)
{
?>
我经常使用$errors数组。因此,在所有检查之前定义一个空数组,然后在每个show_error检查中,将该字符串添加到errors数组中:
$errors[] = "Friend's name is not valid.";
然后在最后,检查错误数组是否为空。如果是,那就没有什么失败。否则,您现在就有了一个包含所有错误的数组,您可以按照自己的喜好显示这些错误。