doushiposong30622 2015-05-10 02:21
浏览 115
已采纳

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

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 2015-05-10 02:40
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog