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条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料