使用PHP请求错误信息并在错误出现时发布

使用PHP请求错误信息并在错误出现时发布,php,validation,forms,Php,Validation,Forms,我有一个HTML表单,它接收输入的数据并通过mail()函数发送。我还有一些验证输入的技术,我创建了一个数组变量$errors来记录所有的错误;比如说, 如果名称为空,$errors[]=“name empty”; 如果电子邮件为空,$errors[]=“email empty” 等等 我能够使用以下技术报告错误: print '<div id="formfeedback"><h3>Error!</h3><p>The following error

我有一个HTML表单,它接收输入的数据并通过mail()函数发送。我还有一些验证输入的技术,我创建了一个数组变量$errors来记录所有的错误;比如说,

如果名称为空,$errors[]=“name empty”; 如果电子邮件为空,$errors[]=“email empty”

等等

我能够使用以下技术报告错误:

print '<div id="formfeedback"><h3>Error!</h3><p>The following error(s) has occurred:<br />';
    foreach ($errors as $msg) { //prints each error
            print " - $msg<br />\n";
        } // end of foreach
print'错误 出现以下错误:
; foreach($errors as$msg){//打印每个错误 打印“-$msg
\n”; }//foreach的结尾
然而,我想要的是以下内容。我希望页面重定向回用于输入信息的原始表单(我知道确切的链接位置,因此我可以使用页眉()甚至
将我带回表单页面)

另外,在表单上,我希望能够在某个div中发布表单上方的错误(称之为div=errors)

我能做到以下几点吗

    <div id="errors">
<?php    
print 'The following error(s) has occurred:<br />';
            foreach ($_REQUEST[$errors] as $msg) { //prints each error
                    print " - $msg<br />\n";
                } // end of foreach
?>   
 </div>

非常感谢


Amit

通常我会让同一个页面处理输入和提交。如果数据有效,邮件将被发送,页面将通知他们(或将他们重定向到其他地方)…如果数据无效,则表单将再次出现,并且可以显示错误,而无需任何奇特的重定向。

最简单的方法是:

// Start the session
session_start();

// Store the errors in the session
$_SESSION['errors'] = $errors;

// Redirect to correct page
header('HTTP/1.1 303 See Other');
header('Location: http://original/page');
exit;
然后,在表单页面上:

// Start the session
session_start();

// extract the errors
$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : array();

// Display the form with errors
foreach ($errors as $msg) ... ;

确保在应用程序顶部启动会话

包括这个基本类

class FormErrors
{
    var $handler;
    function __construct($fname)
    {
        $this->handler &= isset($_SESSION[$fname]) $_SESSION[$fname] : ($_SESSION[$fname] = array());
    }

    public function add($name, $value)
    {
        $this->handler[$name] = $value;
    }

    public function remove($name)
    {
        unset($this->handler[$name]);
    }

    public function getErrors()
    {
        return $this->handler;
    }
}
因此,当您处理错误时,您可以

if(isset($_POST))
{
    $FormErrors = new FormErrors("registration");

    if(strlen($_POST['username']) == 0)
    {
       $FormErrors->add('Username','Please enter a valid username');
    }

    //And for the rest of your checks
}
那么在你的html里面呢

foreach($FormErrors ->getErrors() as $name => $error)
{
    echo sprintf("<p title=\"%s\">%s</p>",$name,$error);
}

我同意@Fosco。我想再解释一下-

可能有两种情况- 1.你正在做原始php 2.您正在任何php框架(如CI或您自己的)上编码

这将有助于识别错误字段并更改样式,以获得更好的用户响应。最后的输入数据保持原样

  • 您正在使用原始php 在这种情况下,您可以在同一文件/页面中接收输入数据。 稍后我将做一个常见的示例

  • 您可以在任何php框架(如CI或您自己的框架)上进行编码。 在这种情况下,加载视图文件以显示表单页面,并且可以在加载时将数据传递给视图页面/文件

  • 对于以上两种情况,您可以进行如下编码-

    /* 
    your input validation and verification goes here. where $error is generated too
    In addition add some error status in above section, 
    you can do it in your $error array too. Also you store received data into $data here. index of $data should be similar as (corresponding) HTML input name. 
    You can do it like below
    */
    $error_stat = array();
    //if the input field name is "email" and email input data raises any error then
    
    $error_stat['email'] = true;
    // same for name
    $error_stat['name'] = true;
    // and so on
    
    // now decide whether you will back to the form page or send the email and do other tasks
    if(count($error_stat)<= 0){
      // send email
      // do aditional tasks
    }
    else{
      // load the form again if its aframework or the form is in seperate file
      // off course send $error,$data and $error_stat to the form page/file
    }
    
    // now here is a code segment of form page
    <?php if(isset($error) && count($error)>0):?>
    <div id="error-msg">
    <?php
    //display errors here
    ?>
    </div>
    <?php endif;?>
    
    <form .... >
    <input type="text" name="email" class="<?php echo (isset($error_stat['email'])?'error':'else'); ?>" value="<?php echo $data['email'];?>" />\
    <!-- and so on ... -->
    
    /*
    您的输入验证和验证将在此处进行。此处也会生成$error
    此外,在上述章节中添加一些错误状态,
    您也可以在$error数组中执行此操作。您还可以将接收到的数据存储到此处的$data中。$data的索引应与(相应的)HTML输入名称类似。
    你可以像下面这样做
    */
    $error_stat=array();
    //如果输入字段名为“email”,并且email输入数据引发任何错误,则
    $error_stat['email']=true;
    //名称相同
    $error_stat['name']=true;
    //等等
    //现在决定是返回表单页面还是发送电子邮件并执行其他任务
    如果(计数($error\u stat)
    
    哦,还有最后一件事,这个表单位于wordpress页面上。我如何将PHP输入wordpress页面?即使我使用带有原始HTML插件的HTML编辑器,它还是以段落形式输入?重定向用户有助于避免刷新页面再次提交数据的问题。另外,您可以将表单显示分离为控件ller A和表单解析到控制器B。如果您的用户在注销后提交表单也很有用(将用户重定向到登录:用户登录,返回表单,表单被填充,因为数据在$会话中)。这看起来不错。我想知道,下面的头做了什么?头('HTTP/1.1 303请参阅其他');我曾经有过header()没有实际重定向我的时候,可能是因为我缺少那一行吗?默认情况下,header('Location:…')使用302 HTTP状态,根据HTTP的某些解释,这将导致浏览器将相同的请求提交到新位置(在这种情况下,使用相同变量的帖子)。使用303会导致它执行GET,丢弃任何POST参数。@Nillocket:虽然这会很好地工作,但这会使$\u会话更重,因此这不是一个好做法。@Saadt:True。通常,表单数据在显示时会从会话中删除,因此内存只会“泄漏”当用户不遵循重定向时。是否可以使用wordpress页面运行此操作?
    /* 
    your input validation and verification goes here. where $error is generated too
    In addition add some error status in above section, 
    you can do it in your $error array too. Also you store received data into $data here. index of $data should be similar as (corresponding) HTML input name. 
    You can do it like below
    */
    $error_stat = array();
    //if the input field name is "email" and email input data raises any error then
    
    $error_stat['email'] = true;
    // same for name
    $error_stat['name'] = true;
    // and so on
    
    // now decide whether you will back to the form page or send the email and do other tasks
    if(count($error_stat)<= 0){
      // send email
      // do aditional tasks
    }
    else{
      // load the form again if its aframework or the form is in seperate file
      // off course send $error,$data and $error_stat to the form page/file
    }
    
    // now here is a code segment of form page
    <?php if(isset($error) && count($error)>0):?>
    <div id="error-msg">
    <?php
    //display errors here
    ?>
    </div>
    <?php endif;?>
    
    <form .... >
    <input type="text" name="email" class="<?php echo (isset($error_stat['email'])?'error':'else'); ?>" value="<?php echo $data['email'];?>" />\
    <!-- and so on ... -->