PHP表单验证(不知道如何将其拆分为两个不同的页面)

PHP表单验证(不知道如何将其拆分为两个不同的页面),php,html,ajax,forms,Php,Html,Ajax,Forms,我正在用PHP编写一个联系人表单。我对PHP的了解几乎不存在 我已经尝试了一段时间,让一个HTML表单提交到PHP表单,以验证其文本字段,如果为空,则为必填字段,但无法使任何内容正常工作。我也不知道AJAX,否则的话,我会尝试这样做 因此,我们求助于在HTML页面中使用PHP自身表单 这是当前版本: <?php // define variables and set to empty values $firstNameErr = $lastNameErr = $emailErr = $me

我正在用PHP编写一个联系人表单。我对PHP的了解几乎不存在

我已经尝试了一段时间,让一个HTML表单提交到PHP表单,以验证其文本字段,如果为空,则为必填字段,但无法使任何内容正常工作。我也不知道AJAX,否则的话,我会尝试这样做

因此,我们求助于在HTML页面中使用PHP自身表单

这是当前版本:

<?php
// define variables and set to empty values
$firstNameErr = $lastNameErr = $emailErr = $messageErr = "";
$first_name = $last_name = $email = $message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["first-name"])) {
     $firstNameErr = "First name is required";
   } else {
     $first_name = test_input($_POST["first-name"]);
   }

    if (empty($_POST["last-name"])) {
     $lastNameErr = "Last name is required";
   } else {
     $last_name = test_input($_POST["last-name"]);
   }

   if (empty($_POST["email"])) {
     $emailErr = "Email is required";
   } else {
     $email = test_input($_POST["email"]);
   }

   if (empty($_POST["message"])) {
     $messageErr = "Message is required";
   } else {
     $message = test_input($_POST["message"]);
   }
}

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

我已经在php内容的底部包括了这一点,即在函数测试输入之后。
header('location:php\u mailer\u form.php')它的位置正确吗

但由于某种原因,当我试图访问contact.php表单时,它甚至没有显示出来,而是直接转到php_mailer_form.php底部的错误表单

 if(!$mail->send()) {
        header('location: url/contactError.html');

    } else {
        header('location: url/contactResult.html');

    }
为什么??(如果我需要包括其他信息,请告诉我)

附录3

<?php

session_start();

$first_name = $_SESSION['first-name'];
$last_name = $_SESSION['last-name'];
$email = $_SESSION['email'];
$message = nl2br($_SESSION['message']);

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'host_specified';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'email_specified';                 // SMTP username
$mail->Password = 'password_specified';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; 

$mail->addReplyTo( $email, $first_name );
$mail->addAddress( $email, $first_name );
$mail->addAddress( 'email_specified', 'Staff' );
$mail->From = 'email_specified';
$mail->FromName = 'Staff';


$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Hotel Room Request';
$mail->Body    = $message; 

$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';

if(!$mail->send()) {
    header('location: url/contactError.html');

} else {
    header('location: url/contactResult.html');

}

下面是一个基本的表单发送示例。这可以全部放在一页上。PHP在顶部,在所有html加载到浏览器之前,
html在html页面的
中的任何位置:

编辑: 我已经更新了代码以包含您的PHP电子邮件

<?php
class EmailEngine
    {
        public  static  function Send($settings = false)
            {
                $email          =   (!empty($settings['email']))? $settings['email']:false;
                $first_name     =   (!empty($settings['first-name']))? $settings['first-name']:false;
                $last_name      =   (!empty($settings['last-name']))? $settings['last-name']:false;
                $message        =   (!empty($settings['message']))? $settings['message']:false;
                $alt_message    =   (!empty($settings['alt_message']))? $settings['alt_message']:'To view the message, please use an HTML compatible email viewer!';

                require(__DIR__.'/PHPMailerAutoload.php');
                $mail = new PHPMailer;
                $mail->isSMTP();                                      // Set mailer to use SMTP
                $mail->Host = 'host_specified';  // Specify main and backup SMTP servers
                $mail->SMTPAuth = true;                               // Enable SMTP authentication
                $mail->Username = 'email_specified';                 // SMTP username
                $mail->Password = 'password_specified';                           // SMTP password
                $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
                $mail->Port = 587; 
                $mail->addReplyTo( $email, $first_name );
                $mail->addAddress( $email, $first_name );
                $mail->addAddress( 'email_specified', 'Staff' );
                $mail->From = 'email_specified';
                $mail->FromName = 'Staff';
                $mail->isHTML(true);                                  // Set email format to HTML
                $mail->Subject = 'Hotel Room Request';
                $mail->Body    = $message; 
                $mail->AltBody = $alt_message;

                return $mail->send();
            }
    }

// Just make an error reporting function to return errors
function error_report($val = false)
    {
        $array["first-name"]    =   "First name is required";
        $array["last-name"]     =   "Last name is required";
        $array["email"]         =   "Email is required";
        $array["message"]       =   "A message is required";

        return (isset($array[$val]))? $array[$val] :false;
    }
// Sanitize. I add false so no error is thrown if not set
function sanitize_vals($data = false)
    {
        if(empty($data))
            return false;

        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }


// If a value is posted (any will do from your form) process the rest of the $_POST
if(isset($_POST["first-name"])) {
        // Just loop through the $_POST instead of doing all the manual if/else...
        foreach($_POST as $key => $value) {
                // This specifically processes your email address
                if(($key == 'email')) {
                        // If not valid email, send to errors
                        if(!filter_var($value,FILTER_VALIDATE_EMAIL))
                            $errors[$key]   =   error_report('email');
                        else
                            $payload[$key]  =   $value;
                    }
                // This processes the rest
                else {
                        $value  =   sanitize_vals($value);  
                        // Checks for empty
                        if(empty($value))
                            $errors[$key]       =   error_report($key);
                        else
                            $payload[$key]  =   $value;
                    }
            }
        // If all is good and no errors set, send the email
        if(!isset($errors)) {
                // SEND MAIL HERE.
                $page   =   (EmailEngine::Send($payload))? "Result" : "Error";
                header("Location: url/contact{$page}.html");
                exit;
            }
    }
?>

<form class="ui form"  method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <div class="field">
        <label>First Name</label>
        <input name="first-name" id="first-name" placeholder="First Name" type="text" value="<?php if(!empty($_POST['first-name'])) echo htmlspecialchars($_POST['first-name'],ENT_QUOTES);?>" />
        <span class="error">* <?php if(!empty($errors['first-name'])) echo $errors['first-name'];?></span> </div>
    <div class="field">
        <label>Last Name</label>
        <input name="last-name" id="last-name" placeholder="Last Name" type="text" value="<?php if(!empty($_POST['last-name'])) echo htmlspecialchars($_POST['last-name'],ENT_QUOTES);?>" />
        <span class="error">* <?php if(!empty($errors['last-name'])) echo $errors['last-name'];?></span> </div>
    <div class="field">
        <label>Email</label>
        <input name="email" id="email" placeholder="Email" type="email" value="<?php if(!empty($_POST['email'])) echo preg_replace('/[^0-9a-zA-Z\@\.\_\-]/',"",$_POST['email']);?>" />
        <span class="error">* <?php if(!empty($errors['email'])) echo $errors['email'];?></span> </div>
    <div class="field">
        <label>Message</label>
        <textarea rows="2" placeholder="Please type in your message" name="message" id="message"><?php if(!empty($_POST['message'])) echo htmlspecialchars($_POST['message'],ENT_QUOTES);?></textarea>
        <span class="error">* <?php if(!empty($errors['message'])) echo $errors['message'];?></span> </div>
    <button class="ui button" type="submit">Submit</button>
</form>


我不确定我是否完全理解您的意图,但通常最好将表单提交到同一页面,以便您可以报告经常发生的错误(就像您正在做的那样)。不过,您可以做的是,一旦您验证了凭据,设置一个会话变量“$\u session['userisloggedin']”,然后使用“header”将用户发送到您想要的页面(例如pageyoucanolyseeifloggedin.php),并在页面顶部显示php代码“if(!(isset($\u session['userisloggedin'])header(“location:“login.php”)若不允许将其发送回登录屏幕,请参阅page@AndrewB,你好,谢谢你的评论。嗯。关于会话,它与用户登录/注销完全无关。这与转到另一个php页面有关,因此我希望能够在会话模式下收集变量,因为我的理解是,这是能够将变量转到多个页面的唯一方法。@AndrewB,同样基于我上面发布的内容,您认为这是否可接受用于商业用途?请让我知道。你可以使用它,但你可以使用更多的验证。另外,您的表单会将
$\u POST
属性发送到您的其他页面。嗯,我仍然不确定是否完全理解您的意图。如果要保存电子邮件,知道它是正确的,请设置变量$_SESSION['email']=$email$_会话['first-name']=$first\u-name;应该允许您保存会话的所有变量。在尝试使用或分配会话变量Oh wow之前,请记住调用“session_start();”。非常感谢。让我试试,我会给你回复的。我很感激!我有一个问题,我在上面的问题的
附录2下发布了这个问题。非常感谢您的意见。谢谢。页眉用于更改页面。在html发送给用户之前,您正在更改页面。我不知道这个邮件程序是如何工作的,但我想你应该“包括”邮件程序文件,而不是更改到那个页面。i、 e.包括(“php_mailer_form.php”);这样做可以有效地从该文件中提取代码,并将其直接插入调用该文件的文件中。一旦它出现,您就可以使用它定义的任何函数/类。如果您使用header,下面的任何PHP代码都不会运行,因为您将看到这段代码并说“好的,我们需要转到另一个页面并运行它的代码,忘掉这段代码”好的。那么,如何将其发送到另一个php表单?好啊看,我有一个php_mailer_form.php,它处于会话模式,所以它应该从这个表单中收集它。但我如何才能做到这一点呢?我认为在这个自php表单中添加标题可以实现这一点。如果我有点慢,请原谅。
<?php

session_start();

$first_name = $_SESSION['first-name'];
$last_name = $_SESSION['last-name'];
$email = $_SESSION['email'];
$message = nl2br($_SESSION['message']);

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'host_specified';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = 'email_specified';                 // SMTP username
$mail->Password = 'password_specified';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 587; 

$mail->addReplyTo( $email, $first_name );
$mail->addAddress( $email, $first_name );
$mail->addAddress( 'email_specified', 'Staff' );
$mail->From = 'email_specified';
$mail->FromName = 'Staff';


$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Hotel Room Request';
$mail->Body    = $message; 

$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!';

if(!$mail->send()) {
    header('location: url/contactError.html');

} else {
    header('location: url/contactResult.html');

}
<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8">

  <title>Contact</title>



  <!--[if lt IE 9]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->
  <style type="text/css">
    .ui.fixed.sticky + p {
        margin-top: 39px;
      }

      .error {
        color: #FF0000;
      }

  </style>
</head>


<body>

<?php
session_start(); //allows use of session variables

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (!isset($_POST["first-name"])) {
     $firstNameErr = "First name is required";
   } else {
     $first_name = test_input($_POST["first-name"]);
   }

    if (!isset($_POST["last-name"])) {
     $lastNameErr = "Last name is required";
   } else {
     $last_name = test_input($_POST["last-name"]);
   }

   if (!isset($_POST["email"])) {
     $emailErr = "Email is required";
   } else {
     $email = test_input($_POST["email"]);
   }

   if (!isset($_POST["message"])) {
     $messageErr = "Message is required";
   } else {
     $message = test_input($_POST["message"]);
   }

   if(isset($first_name) && isset($last_name) && isset($email) && isset($message))
   {
     $_SESSION['first_name'] = $first_name;
     $_SESSION['last_name'] = $last_name;
     $_SESSION['email'] = $email;
     $_SESSION['message'] = $message;

     header("Location: contact9Sessions.php");
   }
}

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

<div class="ui container">
<div class="ui segment">
  <div>

    <div class="ui fluid five item tabular menu">
      <a class="item" href="index.html">Home</a>
      <a class="item" href="about.html">About</a>
      <a class="item" href="rooms.html">Rooms Info & Rates</a>
      <a class="item" href="book.html">To Book</a>
      <a class="item" href="contact.html">Contact</a>
    </div>

  </div>

<div class="ui two column stackable grid">

<div class="ten wide column">

<form class="ui form"  method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  <div class="field">
    <label>First Name</label>
    <input name="first-name" id="first-name" placeholder="First Name" type="text">
     <?php if(isset($firstNameErr)) print ('<span class="error">* ' . $firstNameErr . '</span>'); ?>
  </div>
  <div class="field">
    <label>Last Name</label>
    <input name="last-name" id="last-name" placeholder="Last Name" type="text">
     <?php if(isset($lastNameErr)) print ('<span class="error">* ' . $lastNameErr . '</span>'); ?>
  </div>
    <div class="field">
    <label>Email</label>
    <input name="email" id="email" placeholder="Email" type="email">
     <?php if(isset($emailErr)) print ('<span class="error">* ' . $emailErr . '</span>'); ?>
  </div>
  <div class="field">
    <label>Message</label>
    <textarea rows="2" placeholder="Please type in your message" name="message" id="message"></textarea>
     <?php if(isset($messageErr)) print ('<span class="error">* ' . $messageErr . '</span>'); ?>
  </div>

  <button class="ui button" type="submit">Submit</button>
</form>
  </div>

  <div class="six wide column">
    <br><br>
    <img class="ui centered large bordered rounded image" src="images/tobereplaced.jpg">
  </div>
</div>

</div>

<div class="ui two column grid">
  <div class="ui left aligned ">
    <p>Left Footer Stuff Here</p>
  </div>

  <div class="ui right aligned">
    <p>Right Footer Stuff Here</p>
  </div>

</div>

</div>



</body>
</html>
<?php
session_start(); //allows use of session variables

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (!isset($_POST["first-name"])) {
     $firstNameErr = "First name is required";
   } else {
     $first_name = test_input($_POST["first-name"]);
   }

    if (!isset($_POST["last-name"])) {
     $lastNameErr = "Last name is required";
   } else {
     $last_name = test_input($_POST["last-name"]);
   }

   if (!isset($_POST["email"])) {
     $emailErr = "Email is required";
   } else {
     $email = test_input($_POST["email"]);
   }

   if (!isset($_POST["message"])) {
     $messageErr = "Message is required";
   } else {
     $message = test_input($_POST["message"]);
   }

   if(isset($first_name) && isset($last_name) && isset($email) && isset($message))
   {
     $_SESSION['first_name'] = $first_name;
     $_SESSION['last_name'] = $last_name;
     $_SESSION['email'] = $email;
     $_SESSION['message'] = $message;

     header("Location: php_mailer_form.php");
   }
}

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



<form class="ui form"  method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  <div class="field">
    <label>First Name</label>
    <input name="first-name" id="first-name" placeholder="First Name" type="text">
     <?php if(isset($firstNameErr)) print ('<span class="error">* ' . $firstNameErr . '</span>'); ?>
  </div>
  <div class="field">
    <label>Last Name</label>
    <input name="last-name" id="last-name" placeholder="Last Name" type="text">
     <?php if(isset($lastNameErr)) print ('<span class="error">* ' . $lastNameErr . '</span>'); ?>
  </div>
    <div class="field">
    <label>Email</label>
    <input name="email" id="email" placeholder="Email" type="email">
     <?php if(isset($emailErr)) print ('<span class="error">* ' . $emailErr . '</span>'); ?>
  </div>
  <div class="field">
    <label>Message</label>
    <textarea rows="2" placeholder="Please type in your message" name="message" id="message"></textarea>
     <?php if(isset($messageErr)) print ('<span class="error">* ' . $messageErr . '</span>'); ?>
  </div>

  <button class="ui button" type="submit">Submit</button>
</form>
<?php
class EmailEngine
    {
        public  static  function Send($settings = false)
            {
                $email          =   (!empty($settings['email']))? $settings['email']:false;
                $first_name     =   (!empty($settings['first-name']))? $settings['first-name']:false;
                $last_name      =   (!empty($settings['last-name']))? $settings['last-name']:false;
                $message        =   (!empty($settings['message']))? $settings['message']:false;
                $alt_message    =   (!empty($settings['alt_message']))? $settings['alt_message']:'To view the message, please use an HTML compatible email viewer!';

                require(__DIR__.'/PHPMailerAutoload.php');
                $mail = new PHPMailer;
                $mail->isSMTP();                                      // Set mailer to use SMTP
                $mail->Host = 'host_specified';  // Specify main and backup SMTP servers
                $mail->SMTPAuth = true;                               // Enable SMTP authentication
                $mail->Username = 'email_specified';                 // SMTP username
                $mail->Password = 'password_specified';                           // SMTP password
                $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
                $mail->Port = 587; 
                $mail->addReplyTo( $email, $first_name );
                $mail->addAddress( $email, $first_name );
                $mail->addAddress( 'email_specified', 'Staff' );
                $mail->From = 'email_specified';
                $mail->FromName = 'Staff';
                $mail->isHTML(true);                                  // Set email format to HTML
                $mail->Subject = 'Hotel Room Request';
                $mail->Body    = $message; 
                $mail->AltBody = $alt_message;

                return $mail->send();
            }
    }

// Just make an error reporting function to return errors
function error_report($val = false)
    {
        $array["first-name"]    =   "First name is required";
        $array["last-name"]     =   "Last name is required";
        $array["email"]         =   "Email is required";
        $array["message"]       =   "A message is required";

        return (isset($array[$val]))? $array[$val] :false;
    }
// Sanitize. I add false so no error is thrown if not set
function sanitize_vals($data = false)
    {
        if(empty($data))
            return false;

        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }


// If a value is posted (any will do from your form) process the rest of the $_POST
if(isset($_POST["first-name"])) {
        // Just loop through the $_POST instead of doing all the manual if/else...
        foreach($_POST as $key => $value) {
                // This specifically processes your email address
                if(($key == 'email')) {
                        // If not valid email, send to errors
                        if(!filter_var($value,FILTER_VALIDATE_EMAIL))
                            $errors[$key]   =   error_report('email');
                        else
                            $payload[$key]  =   $value;
                    }
                // This processes the rest
                else {
                        $value  =   sanitize_vals($value);  
                        // Checks for empty
                        if(empty($value))
                            $errors[$key]       =   error_report($key);
                        else
                            $payload[$key]  =   $value;
                    }
            }
        // If all is good and no errors set, send the email
        if(!isset($errors)) {
                // SEND MAIL HERE.
                $page   =   (EmailEngine::Send($payload))? "Result" : "Error";
                header("Location: url/contact{$page}.html");
                exit;
            }
    }
?>

<form class="ui form"  method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <div class="field">
        <label>First Name</label>
        <input name="first-name" id="first-name" placeholder="First Name" type="text" value="<?php if(!empty($_POST['first-name'])) echo htmlspecialchars($_POST['first-name'],ENT_QUOTES);?>" />
        <span class="error">* <?php if(!empty($errors['first-name'])) echo $errors['first-name'];?></span> </div>
    <div class="field">
        <label>Last Name</label>
        <input name="last-name" id="last-name" placeholder="Last Name" type="text" value="<?php if(!empty($_POST['last-name'])) echo htmlspecialchars($_POST['last-name'],ENT_QUOTES);?>" />
        <span class="error">* <?php if(!empty($errors['last-name'])) echo $errors['last-name'];?></span> </div>
    <div class="field">
        <label>Email</label>
        <input name="email" id="email" placeholder="Email" type="email" value="<?php if(!empty($_POST['email'])) echo preg_replace('/[^0-9a-zA-Z\@\.\_\-]/',"",$_POST['email']);?>" />
        <span class="error">* <?php if(!empty($errors['email'])) echo $errors['email'];?></span> </div>
    <div class="field">
        <label>Message</label>
        <textarea rows="2" placeholder="Please type in your message" name="message" id="message"><?php if(!empty($_POST['message'])) echo htmlspecialchars($_POST['message'],ENT_QUOTES);?></textarea>
        <span class="error">* <?php if(!empty($errors['message'])) echo $errors['message'];?></span> </div>
    <button class="ui button" type="submit">Submit</button>
</form>