doushiposong30622
doushiposong30622
2015-05-10 02:21

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

  • validation
  • php
  • email
已采纳

I am trying to teach myself how to create a contact form and have got it working to a point where I can send emails to the set email address and validate the email address but would also like to validate the other input fields but am having trouble with this. I have tried only validating the name but cannot get the regular expression condition to work and am not sure on if it is best pulling back all the validation errors in one variable.

Not if the foreach loop on the if empty is confusing things more than they should be or not.

Any advise will be much appreciated.

Below the index.php code.

<?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']);

?>

and the mail.php code

<?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条回答

  • dousong3760 dousong3760 6年前

    The problem is your regex just looks for one of the accepted characters to occur. Instead, you should check if any invalid characters occur with a double negative.

    $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]/ looks for any characters not included in the braces and the ! takes the opposite result. It will only be true if those characters are the only ones present in the string.

    点赞 评论 复制链接分享
  • doushibu2453 doushibu2453 6年前

    Please try this code to validate the email form:

    $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."; 
    }
    

    Or you can use :

    filter_var($fields['email'], FILTER_VALIDATE_EMAIL) && preg_match($regex, $fields['email'])
    

    And please use empty rather than isset hope this help you a little. :)

    点赞 评论 复制链接分享

为你推荐