简体   繁体   English

当用户使用PHP提交消息时,如何在同一页面上添加错误或成功消息

[英]How to add a error or sucess message on the same page, when the user submits a message in PHP

I want to know how to add a error or sucess message on the same page, when the user submits a message, with all fields correct. 我想知道如何在用户提交消息且所有字段正确的情况下在同一页面上添加错误或成功消息。
PS:I am working on localhost and know very little of PHP, so please explain like I'm 5. Thanks PS:我在localhost上工作,对PHP的了解很少,所以请像我5岁时解释一下。谢谢

 <?php

    $errorMSG = "";

    // NAME
    if (empty($_POST["name"])) {
        $errorMSG = "Por favor preencha o seu nome ";
    } else {
        $name = $_POST["name"];
    }

    // EMAIL
    if (empty($_POST["email"])) {
        $errorMSG .= "Por favor preencha com o seu email ";
    } else {
        $email = $_POST["email"];
    }

    // MSG SUBJECT
    if (empty($_POST["msg_subject"])) {
        $errorMSG .= "Por favor escreva um assunto da mensagem";
    } else {
        $msg_subject = $_POST["msg_subject"];
    }


    // MESSAGE
    if (empty($_POST["message"])) {
        $errorMSG .= "Por favor escreva uma mensagem ";
    } else {
        $message = $_POST["message"];
    }

    //email here
    $EmailTo = "email@hotmail.com";
    $Subject = "New Message Received";

    //email body text
    $Body = "";
    $Body .= "Nome: ";
    $Body .= $name;
    $Body .= "\n";
    $Body .= "Email: ";
    $Body .= $email;
    $Body .= "\n";
    $Body .= "Assunto: ";
    $Body .= $msg_subject;
    $Body .= "\n";
    $Body .= "Mensagem: ";
    $Body .= $message;
    $Body .= "\n";

    // send email
    $success = mail($EmailTo, $Subject, $Body, "De:".$email);

    //success message
    if ($success && $errorMSG == ""){
       echo "sucesso";
    }else{
        if($errorMSG == ""){
            echo "Algo correu mal :(";
        } else {
            echo $errorMSG;
        }
    }

    ?>


    <!DOCTYPE html>
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Title</title>

    <!-- css -->
    <link href="css/contactform.css" rel="stylesheet" />
    <link href="css/bootstrap.min.css" rel="stylesheet" />
    <link href="css/style.css" rel="stylesheet" />
    </head>
    <body>


                            <!-- Start Contact Form -->
    <form role="form" id="contactForm" class="contact-form" data-toggle="validator" class="shake">
      <div class="form-group">
        <div class="controls">
          <input type="text" id="name" class="form-control" placeholder="Nome" required data-error="Por favor escreva o seu nome">
          <div class="help-block with-errors"></div>
        </div>
      </div>
      <div class="form-group">
        <div class="controls">
          <input type="email" class="email form-control" id="email" placeholder="Email" required data-error="Por favor escreva o seu email">
          <div class="help-block with-errors"></div>
        </div>
      </div>
      <div class="form-group">
        <div class="controls">
          <input type="text" id="msg_subject" class="form-control" placeholder="Assunto" required data-error="Por favor escreva o assunto da mensagem">
          <div class="help-block with-errors"></div>
        </div>
      </div>
      <div class="form-group">
        <div class="controls">
          <textarea id="message" rows="7" placeholder="Mensagem" class="form-control" required data-error="Escreva a sua mensagem"></textarea>
          <div class="help-block with-errors"></div>
        </div>  
      </div>

      <button type="submit" id="submit" class="btn btn-effect"><i class="fa fa-check"></i>Enviar</button>
      <div id="msgSubmit" class="h3 text-center hidden"></div> 
      <div class="clearfix"></div>   

    </form>     

Also, I configured sendmail's "sendmail.ini" and "php.ini" file so as to test the receiving of emails on my local server, but keep getting this error: Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing in 另外,我配置了sendmail的“ sendmail.ini”和“ php.ini”文件,以便测试本地服务器上的电子邮件接收,但始终收到此错误: Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing in

What's custom "From:"? 什么是custom "From:"?

you need to add action to your form this way, method and properly submit it.. try this 您需要以这种方式,方法向表单中添加操作,然后正确提交。

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
 </style>
 </head>
 <body>  

 <?php
 // define variables and set to empty values
  $nameErr = $emailErr =  "";
 $name = $email =  "";

  if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
  $nameErr = "Name is required";
   } else {
   $name = test_input($_POST["name"]);
   // check if name only contains letters and whitespace
   if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
    $nameErr = "Only letters and white space allowed";
    }
   }

    if (empty($_POST["email"])) {
     $emailErr = "Email is required";
    } else {
     $email = test_input($_POST["email"]);
     // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format";
     }
    }


     }

     function test_input($data) {
       $data = trim($data);
     $data = stripslashes($data);
     $data = htmlspecialchars($data);
   return $data;
   }
   ?>


    <p><span class="error">* required field.</span></p>
    <form method="post" action="<?php echo      htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
   Name: <input type="text" name="name" value="<?php echo $name;?>">
   <span class="error">* <?php echo $nameErr;?></span>
   <br><br>
   E-mail: <input type="text" name="email" value="<?php echo $email;?>">
    <span class="error">* <?php echo $emailErr;?></span>
     <br><br>

    <input type="submit" name="submit" value="Submit">  
    </form>

    <?php
    echo "<h2>Your Input:</h2>";
     echo $name;
     echo "<br>";
     echo $email;
     echo "<br>";

   ?>

    </body>
    </html>

Before i explain further, i have to point out that you didn't define or specify action attribute in your form. 在我进一步解释之前,我必须指出,您没有在表单中定义或指定动作属性。 Your php code in it written form can't work, firstly you have to add action and method attribute to form element like this 您以书面形式编写的php代码无法正常工作,首先,您必须将action和method属性添加到这样的表单元素中

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"   method="post">
  //input element here
</form>

The action attribute point to location of script(PHP file in your case) that will process the form data submitted by the user, but in your case, you want the php itself to process the form data, the $_SERVER["PHP_SELF"] contain the current php file location. action属性指向脚本的位置(在您的情况下为PHP文件),该脚本将处理用户提交的表单数据,但是在您的情况下,您希望php本身处理表单数据,即$ _SERVER [“ PHP_SELF”]包含当前的php文件位置。 For security reason, the php super global "$_SERVER" is wrap inside "htmlspecialchars" function, which escape the spacial characters. 出于安全原因,php超级全局变量“ $ _SERVER”被包装在“ htmlspecialchars”函数内,该函数转义了空格字符。 Secondly, because your submitting the form to the same php script, you have to check whether the form has been submitted, not when user visit the php page using $_SERVER["REQUEST_METHOD"]. 其次,因为您将表单提交到相同的php脚本,所以您必须检查表单是否已提交,而不是当用户使用$ _SERVER [“ REQUEST_METHOD”]访问php页面时。 If the REQUEST_METHOD is POST, then the form has been submitted, example: 如果REQUEST_METHOD是POST,则表单已提交,例如:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  //put your validation code here
}

To make it clearer, this is how your php code suppose look like: 更清楚地说,这就是您的php代码的样子:

<?php
  //global variables here
  $errorMSG = "";
  $name = "";
  $email = "";
  $msg_subject = "";
  $message = "";
  $EmailTo = "";
  $Subject = "";
  $Body = "";

  //check if user submitted a form
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // NAME
    if (empty($_POST["name"])) {
      $errorMSG = "Por favor preencha o seu nome ";
    }
    else {
      $name = $_POST["name"];
    }

    // EMAIL
    if (empty($_POST["email"])) {
      $errorMSG .= "Por favor preencha com o seu email ";
    } 
    else {
      $email = $_POST["email"];
    }

    // MSG SUBJECT
    if (empty($_POST["msg_subject"])) {
      $errorMSG .= "Por favor escreva um assunto da mensagem";
    }
    else {
      $msg_subject = $_POST["msg_subject"];
    }

    // MESSAGE
    if (empty($_POST["message"])) {
      $errorMSG .= "Por favor escreva uma mensagem ";
    } 
    else {
      $message = $_POST["message"];
    }

    //email here
    $EmailTo = "email@hotmail.com";
    $Subject = "New Message Received";

    //email body text
    $Body = "";
    $Body .= "Nome: ";
    $Body .= $name;
    $Body .= "\n";
    $Body .= "Email: ";
    $Body .= $email;
    $Body .= "\n";
    $Body .= "Assunto: ";
    $Body .= $msg_subject;
    $Body .= "\n";
    $Body .= "Mensagem: ";
    $Body .= $message;
    $Body .= "\n";

    // send email
    $success = mail($EmailTo, $Subject, $Body, "De:".$email);

    //success message
    if ($success && $errorMSG == ""){
      echo "sucesso";
    }
    else{
      if($errorMSG == ""){
        echo "Algo correu mal :(";
      }
      else {
        echo $errorMSG;
      }
    }
  }
?>

I notice that all your input element has no name attribute, which is the name your php script use to access the form data submitted by the user, this is right way to do it: 我注意到您所有的input元素都没有name属性,这是您的php脚本用来访问用户提交的表单数据的名称,这是正确的方法:

<input type="text" name="username" placeholder="Enter your name"/>

Another thing you have to take note of, php code execute before the html and JavaScript had a chance. 您还需要注意的另一件事是,php代码在html和JavaScript出现之前就已执行。

Don't use this for production php code, for more information on how to correctly do this, visit this website https//www.w3schools.com/php/ 不要将此用于生产php代码,有关如何正确执行此操作的更多信息,请访问此网站https://www.w3schools.com/php/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM