如何验证电子邮件地址

时间:2011-10-20 16:36:53

标签: php javascript ajax

  

可能重复:
  How to validate an email address in PHP

我想知道有人可以帮助我。

我需要验证以下代码的电子邮件地址,但遇到问题。

<?php

if ($_POST) {

    $expected = array('name', 'email', 'emailmessage');
    $validation = array(
        'name'          => 'Please provide your full name',
        'email'         => 'Please provide your valid email address',
        'emailmessage'  => 'Please provide message'
    );

    $errors = array();
    $output = array();

    foreach($expected as $key) {

        $input = htmlspecialchars($_POST[$key]);

        if (array_key_exists($key, $_POST)) {
            if (empty($_POST[$key])) {
                $errors[$key] = $validation[$key];
            } else {
                $output[$key] = $_POST[$key];
            }
        } else {
            $errors[$key] = $validation[$key];
        }

    }

    if (!empty($errors)) {
        $array = array('error' => true, 'fields' => $errors);
    } else {

        // PROCESS FORM

    // ---------------------------------------------------------
    // BEGIN EDITING
    // ---------------------------------------------------------

    $to = "qakbar@hotmail.co.uk"; //This is the email address messages will be sent to
    $web_name = "My Test Web Form"; //This is the name of your website that will show in your email inbox

    //get IP address
    $ip = $_SERVER['REMOTE_ADDR'];

    //make time
    $time = time();
    $date = date("r", $time);

    // ---------------------------------------------------------
    // END EDITING
    // ---------------------------------------------------------

    $emailmessage = trim($emailmessage);
    $emailmessage = nl2br($emailmessage);
    $emailmessage = htmlspecialchars($emailmessage);
    $emailmessage = wordwrap($emailmessage, 70);

    //Visible form elements
    $name = $_POST['name']; //Sender's name
    $email = $_POST['email']; //Sender's email
    $emailmessage = htmlspecialchars($_POST['emailmessage']); //Sender's message

    //Setting up email
    $subject = "New Message from $web_name";

    $message = "
                New message from $name <br/><br/>

                Message:<br />
                $emailmessage
                <br/>

                <br/>
                Email: $email<br />
                IP:</strong> <span style=\"color:#990000;\">$ip</span><br />
                Date:</strong> $date

                ";

    $header  = 'MIME-Version: 1.0' . "\r\n";
    $header .= 'Content-type: text/html; charset=utf-8' . "\r\n";
    $header .= 'From:'. $email . " \r\n";

    $sent = mail($to, $subject, $message, $header);

        //$message = '<div id=message>You have successfully subscribed to our newsletter</div>';
        $array = array('error' => false, 'message' => $message);
    }

    echo json_encode($array);
}

我希望电子邮件在$ validation数组中验证,因为我的消息通过此消息并需要电子邮件验证才能执行此操作。

我试图使用以下内容,但不知道放在哪里或如何调用它。

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

    // email is valid

} else {

    // email is invalid

}

任何帮助都非常适合。

谢谢

3 个答案:

答案 0 :(得分:1)

您可以像这样使用它:

filter_var($email, FILTER_VALIDATE_EMAIL)  or  die("Email wrong.");

在您分配了这个确切的变量之后:

$email = $_POST['email'];

当然,这种结构可能更合理,也可以提供更好的错误通知。但听起来好像你需要先用PHP进行更多的一般练习。

答案 1 :(得分:0)

您的代码奇怪:

    $input = htmlspecialchars($_POST[$key]);

    if (array_key_exists($key, $_POST)) {

在检查密钥是否存在之前,您已经使用了密钥。同样,$ input变量在代码中不再使用,因此它是无用的行。

答案 2 :(得分:-1)

可能,这段代码会对你有所帮助。试试吧。

<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
    $name = $_POST['uname'];
    $email = $_POST['email'];

    $valid_arr = array();
    $error_arr = array();

        if($name == ''){
            $error_arr['name'] = 'Required';
        }
        else if(!preg_match('/^[a-zA-A]+$/',$name)){
            $error_arr['name'] = 'Please put correct value';
        }
        else{
            $valid_arr['name'] = $name;
        }

        if($email == ''){
                $error_arr['email'] = 'Required';
            }
            else if(!preg_match('/^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/',$email)){
                $error_arr['email'] = 'Exm.- john@gmail.com';
            }
            else{
                $valid_arr['email'] = $email;
            }

            if(count($error_arr) == 0){
                header('location: success.php');
            }
            else{
                echo 'Error in Loading';
            }
}
?>
<html>
<head>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST">
    <table>
    <tr>
        <td><label>User Name :</label></td>
        <td><input type="text" name="uname" value="<?php echo $valid_arr['name'];?>"/></td>
        <td class="error"><?php echo $error_arr['name'];?></td>
    </tr>
    <tr>
        <td><label>Email :</label></td>
        <td><input type="text" name="email" value="<?php echo $valid_arr['email'];?>"/></td>
        <td class="error"><?php echo $error_arr['email'];?></td>
    </tr>
    <tr>
        <td><input type="submit" name="save" value="Submit"/></td>
    </tr>
    </table>
</form>
</body>
</html>