如何结合表单验证和phpmailer ...?

时间:2015-09-10 22:33:21

标签: php forms phpmailer

我正在尝试使用PHPMailer通过电子邮件发送基本联系表单。

此表格适合我:

<?php

$first_name = check_input($_POST['first-name'], "Please enter your name");
$last_name = check_input($_POST['last-name'], "Please enter your last name");
$email = check_input($_POST['email'], "Please enter your email address");
$message = check_input(nl2br($_POST['message']), "Please enter your message");


require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

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

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = '';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '';                 // SMTP username
$mail->Password = '';                           // 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( 'blah@fake.org', 'Staff' );
$mail->From = 'blah@fake.org';
$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: a_url_here');

} else {

        function check_input($data, $problem = ' ')
        {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            if ($problem && strlen($data) == 0)
            {
                show_error($problem);
            }
            return $data;
            }

}
?>

现在,我正在尝试将其与错误检查结合起来。不知道如何结合它仍然使它工作。这就是我到目前为止所做的事情,它在提交时都是空白。我不知道把check_input函数放在哪里,所以我把它放在底部的else部分。如何使此表格起作用,这样不仅可以验证用户的输入,还可以通过电子邮件发送出去?

create table if not exists person(
      id integer primary key not null, --auto increment key
      name text NOT NULL
      );

begin transaction;

insert into person(name) values ('señor');

end transaction;

2 个答案:

答案 0 :(得分:1)

创建所谓的validator类:

class Validator {

    // set of rules for validator
    // syntax: <field-name> => '<list-of-rules, joined-with-pipe>',
    protected $rules = [
        'first-name' => 'required',
        'last-name' => 'required',
        'message' => 'required',
        'email' => 'required|email',
    ];

    // message to show if concrete field-rule failed
    // ":field" will be replaced with field actual name
    protected $messages = [
        'required' => 'Field :field is required',
        'nonzero' => 'Field :field must not be zero'
        'email' => 'Field :field must represent an emai address'
    ]; 

    protected $errors;

    // call this to validate provided $input
    function validate($input) {

        $errors = [];

        // for each defined field-ruleset
        foreach ($this->rules as $field => $rules) {
            $rules = explode('|', $rules);
            // for each rule
            foreach ($rules as $rule)
                // call function with name "checkNameofrule"
                if (!$this->{"check" . ucfirst($rule)}($input, $field))
                    // memorize error, if any
                    $errors[$field][] = $this->error($field, $rule);
        }

        // validation passed if there are no errors
        return !($this->errors = $errors);
    }

    function errors() {
        return $this->errors;
    }

    function error($field, $error) {
        return str_replace(':field', $field, $this->messages[$field]);
    }

    // check for required fields
    function checkRequired($input, $field) {
        if (!isset($input[$field]))
            return false;

        return trim(htmlspecialchars(stripslashes($input[$field]))) != '';
    }

    // check for valid email
    function checkEmail($input, $field) {
        return !!preg_match('#.+@[^.]+\..+#', @$input[$field]);
    }

    // other custom checks
    function checkNonzero($input, $field) {
        return intval(@$input[$field]) != 0;
    }

}

并像这样使用它:

$validator = new Validator();

// validating...
if (!$validator->validate($_POST)) {
    // looks like there are errors in input

    echo "<div class=\"errors\">";
    echo "<b>Looks like you have errors in input:</b><br />";
    foreach ($validator->errors() as $field => $errors) {
        foreach ($errors as $error)
            echo "<p>{$error}</p>";
    }
    echo "</div>";

} else {

    // input had passed validation, send email...

    require 'PHPMailerAutoload.php';

    $mail = new PHPMailer;

    ...

    if(!$mail->send()) {
        header('location: a_url_here');
    } else {
        header('location: a_url_here');
    }

}

答案 1 :(得分:0)

您不应在一个文件中验证和呈现表单。它导致可维护性差,并以令人讨厌的方式混合责任。尝试像这样构建项目:

form.php
validate-and-send.php

表单包含<form action=validate-and-send.php ...><input ...。 另一个文件包含验证和发送的逻辑。像这样:

<?php
$email = filter_var($_REQUEST['email'], FILTER_VALIDATE_EMAIL);

if ($email) {
    ....
}

if (/*all fields valid*/) {
   // phpmailer code
} else {
   // redirect back to form
}

棘手的部分是重定向回形式。您可以使用标头重定向并通过get-parameters Location form.php?name=validname设置所有有效字段,也可以将它们填入$ _SESSION并以会话形式输出。

更进一步的是通过AJAX提交并以验证结果作为JSON进行响应。所以流程就像

1. form.submit() -> ajax -> validate-and-send.php
2a. validate-and-send.php -> "OK" -> form.php
2b. validate-and-send.php -> JSON: { errors: [ {reason: "bad name"}, {reason: "bad email"}]} 
      -> form.php
3. Display what happened with JS.