验证表单PHP并发送到电子邮件

时间:2016-04-08 01:00:09

标签: php html forms validation

我正在尝试验证电子邮件表单,并将有效结果发送到我的电子邮箱。

从我收集的内容来看,PHP位于索引页面的顶部,并通过

调用它。
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="post">

从我的表格。当我尝试提交表单时,我的页面会加载到一个空白页面,说它无法找到

myurl.com/<?php%20echo%20htmlentities($_SERVER[%27PHP_SELF%27]);?>

我哪里错了?这是我的PHP:

      <?php
    //my variables, email, emailerr set to 0
        $email = "";
        $emailErr = "";
        $subject = "Subscription";
        $recipient = "myemail@gmail.com";
        $location = "index.php";
        $sender = $recipient;
        $body .= "".$_REQUEST["$email"]." \n";

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

        //check if field is empty
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            if (empty($_POST["email"])) {
            $emailErr = "Please enter a valid e-mail address.";
        } else {

          //send to function test_input($data) to validate format
          $email = test_input($_POST["email"]);
          if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
              $emailErr = "Invalid e-mail format!";
        } else {

        //if successful mail subscription and return to main page 
        mail( $recipient, $subject, $body, "From: $sender" ) or die ("Mail could not be sent.");

        header(Location: $location" );

        }
        ?>

和我的HTML:

      //my form
            <form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="post">

    <div class="input">

    <input type="text" class="button" id="email" name="email" placeholder="NAME@EXAMPLE.COM">

<span class="error"><?php echo $emailErr;?></span> 

<input type="submit" class="button" name="email_submit" id="submit" value="SEND">

0 个答案:

没有答案