php电子邮件表单验证和正则表达式

时间:2015-05-10 02:21:55

标签: php validation email

我正在尝试自学如何创建联系表单并使其工作到我可以发送电子邮件到设置的电子邮件地址并验证电子邮件地址,但也想验证其他输入字段但是我遇到麻烦。 我试过只验证名称,但无法使正则表达式条件起作用,并且不确定是否最好将一个变量中的所有验证错误拉回来。

如果if空的foreach循环比他们应该更多地混淆了东西,那就不行了。

任何建议都将不胜感激。

在index.php代码下面。

<?php 
session_start();

// include the security php
require_once 'security.php';



// setting the errors to the session to get rid of the index error message

$errors = isset($_SESSION['errors']) ? $_SESSION['errors'] : [];
$fields = isset($_SESSION['fields']) ? $_SESSION['fields'] : [];
$mailSent = isset($_SESSION['sucess']) ? $_SESSION['sucess'] : [];
$email_ok = isset($_SESSION['validation']) ? $_SESSION['validation'] : [];
$name_ok = isset($_SESSION['validation']) ? $_SESSION['validation'] : [];
// print_r($email_ok);
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="uft-8">
    <title>demo contact form</title>
    <style type="text/css">
     input{
        display: block;
     }
     div.main{
        display: block;
        width: 960px;
        margin: 0 auto;
     }
     .warning{
        color: red;
     }
    </style>
</head>
<body>
<div class="main">

<!-- error message display -->

    <?php if(!empty($errors)): ?>
        <div class="panel warning">
            <ul><li><?php echo implode('</li><li>', $errors); ?></li></ul>
        </div>
    <?php endif; ?> 


    <?php if(!empty($mailSent)): ?>
        <div class="panel">
            <p><?php echo ($mailSent); ?></p>
        </div>
    <?php endif; ?>


    <form action="mail.php" method="post">
        <input type="text" name="name" placeholder="Your name" <?php echo isset($fields['name']) ? 'value="' .e($fields['name']). '"' : ''?>/>
        <?php 
            if(!empty($name_ok)): ?>
                <p class="warning"><?php echo ($name_ok[0]); ?></p>
            <?php endif; 
        ?>

        <input type="text" name="email" placeholder="example@email.com" <?php echo isset($fields['email']) ? 'value="' .e($fields['email']). '"' : ''?>/>
        <?php 
            if(!empty($email_ok)): ?>
                <p class="warning"><?php echo ($email_ok[0]); ?></p>
            <?php endif; 
        ?>

        <textarea name="message"><?php echo isset($fields['message']) ?  e($fields['message']) : ''?></textarea>

        <input type="submit" name="submit" value="Send">
    </form>
</div>



</body>
</html>

<?php
// destroy the session so if the user moves away from the page and comes back the prior sessions will be gone
unset($_SESSION['errors']);
unset($_SESSION['fields']);
unset($_SESSION['sucess']);
unset($_SESSION['validation']);

?>

和mail.php代码

<?php

// start session to pass data around
session_start();

// include the php mailer files
require_once 'libs/phpmailer/PHPMailerAutoload.php';


$errors = [];
$validation = [];
$ok_name = '/[a-zA-Z\s]+/';
// checking what is set in the post array
if(isset($_POST['name'], $_POST['email'], $_POST['message'])){
    // echo "all set";

    // place all inputs into a varible so that we can out but them on for each loops
    $fields = [
        'name' => trim($_POST['name']),
        'email' => trim($_POST['email']),
        'message' => trim($_POST['message'])
    ];

    foreach ($fields as $field => $data) {
        // checking if a field is empty
        echo '<pre>'.print_r($field).'</pre>';
    die();
        if(empty($data)){
            $errors[] = 'The '.$field. ' field is required';
        }
        elseif
            (filter_var($fields['email'], FILTER_VALIDATE_EMAIL) == false){
                $validation[] = 'Enter a corect email address'; 
        }
        elseif(preg_match($ok_name, $fields['name']) == false){
            $validation[] = 'Use only letters and spaces';
        }
    }

// name validation


// email address valiadtion




    // send email via phpmailer

    // if the $errors are empty
    if(empty($errors || $validation)){


        $m = new PHPMailer;// set a new instance of phpmailer
        // these are teh details to connect to gmail via smtp
        $m->isSMTP();
        $m->SMTPAuth = true;
        $m->Mailer = 'smtp';
        $m->Host = 'smtp.example.com';
        $m->Username = 'example@example.com';
        $m->Password = 'nottelling';
        $m->SMTPSercure = 'tls';// ssl
        $m->Port = 587;// 465
        $m->isHTML();// for messages that include html
        $m->Subject = 'Contact form Protfolio website';
        $m->Body = 'From: '.$fields['name']. '('.$fields['email'].')<p>'.$fields['message'].'</p>';
        $m->FromName = 'Contact';
        $m->SMTPDebug = 2;
        $m->AddReplyTo($fields['email'], $fields['name']);
        $m->addAddress('example@example.com', 'Name Name');

        if($m->send()){
            $_SESSION['sucess'] = 'Thank you for your email, I will be in touch soon.';
            header('location: index1.php');
            die();
        }
        else{
            $errors[] = 'Sorry, could not send your email.';
        }

    }

}
else{
    $errors[] = 'something went wrong';
}

// save the error message to the sessions super golbal variable
$_SESSION['errors'] =$errors;
// save input data for a sticky form
$_SESSION['fields'] =$fields;

$_SESSION['validation'] =$validation;

// redirect back to the page
header('location: index1.php');

?>

2 个答案:

答案 0 :(得分:0)

请尝试使用此代码验证电子邮件表单:

rs.getString("sum");

或者您可以使用:

$email = "test@email"; // Invalid email address, put your `$fields['email']`
$regex = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$";
if (preg_match( $regex, $email ) ) {
    echo $email . " is a valid email."; 
} else { 
    echo $email . " is an invalid email."; 
}

请使用filter_var($fields['email'], FILTER_VALIDATE_EMAIL) && preg_match($regex, $fields['email']) 而不是empty希望这对您有所帮助。 :)

答案 1 :(得分:0)

问题是你的正则表达式只是寻找一个可接受的字符。相反,您应该检查是否有任何无效字符出现双重否定。

$errors = [];
$validation = [];
$bad_name = '/[^a-zA-Z\s]/';
//...
        elseif(!preg_match($ok_name, $fields['name']) == false){
            $validation[] = 'Use only letters and spaces';
        }

/[^a-zA-Z\s]/查找大括号中未包含的任何字符,!采用相反的结果。只有当这些字符是字符串中唯一存在的字符时才会出现。