如何在提交给PHP的表单中验证电子邮件地址

时间:2013-05-25 15:48:44

标签: php forms security validation

我正在建立一个小型用户注册系统来尝试教我自己更多的PHP和MySQL。到目前为止,我已经达到了这一点:

   <?php

    $errormsg ="";
    if (isset($_POST['adduser'])){

    $email = $_POST['email'];
    $pword = $_POST['pword'];
    $pword2 = $_POST['pword2'];

    $email = stripslashes($email);
    $email = strip_tags($email);
    $pword = stripslashes($pword);
    $pword = strip_tags($pword);
    $pword2 = stripslashes($pword2);
    $pword2 = strip_tags($pword2);

    if ($email == "") {
        $errormsg ="Error, You must fill in the email box.";
    }
    else if ($pword == "") {
        $errormsg ="Error, You must fill in the password box.";
    }
    else if ($pword2 == "") {
        $errormsg ="Error, You must fill in the repeat password box.";
    }
    else if ($pword != $pword2) {
        $errormsg ="Error, Your passwords don't match!";
    }
    else {
        $errormsg = "Success!";
    }
}
?>

这个回声在当前成功,我计划在完成后将数据添加到数据库中。

如何检查电子邮件是否有效? (例如是“example@example.com”而不仅仅是“rgaegegegege”)

使用stripslashes和标签还有多安全?我还能做些什么才能减少黑客攻击?

感谢您的帮助!

2 个答案:

答案 0 :(得分:4)

filter_var()功能是验证电子邮件,网址等的最简单方法之一。

要验证您可以执行的电子邮件:

if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === true) {
   // valid
}else {
   echo "Email is NOT valid!";
}

答案 1 :(得分:0)

您可以尝试这样

<?php
$email = $_POST['email'];

if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/i", $email)){
      echo 'email is Invalid';

     }
   else {
    echo 'email is correct ';
     }
?>