dongying6659 2013-03-03 22:35
浏览 29
已采纳

PHP验证一次显示所有错误

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条回答 默认 最新

  • duandi1636 2013-03-03 22:39
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程