2

我想创建一个仅接受某些类型的电子邮件地址的注册输入字段(例如,只接受以 结尾的电子邮件地址@yahoo.com),以便我可以在谁可以访问我的网站方面提供一些安全性(例如,我只想接受来自我学校学生的电子邮件地址,即它们必须以@school.edu) 结尾。

这是我到目前为止所拥有的,但这并不区分特定类型的电子邮件:

<?php

    // configuration
    require("../includes/config.php"); 

    // if form was submitted
    if ($_SERVER["REQUEST_METHOD"] == "POST")
    {
        // validate inputs
        if (empty($_POST["username"]))
        {
            apologize("You must provide a username.");
        }
        else if (empty($_POST["password"]))
        {
            apologize("You must provide a password.");
        }
        else if (empty($_POST["confirmation"]) || $_POST["password"] != $_POST["confirmation"])
        {
            apologize("Those passwords did not match.");
        }

        // try to register user
        $results = query("INSERT INTO users (username, hash, cash) VALUES(?, ?, 10000.0000)",
            $_POST["username"], crypt($_POST["password"])
        );
        if ($results === false)
        {
            apologize("That username appears to be taken.");
        }

        // get new user's ID
        $rows = query("SELECT LAST_INSERT_ID() AS id");
        if ($rows === false)
        {
            apologize("Can't find your ID.");
        }
        $id = $rows[0]["id"];

        // log user in
        $_SESSION["id"] = $id;

        // redirect to portfolio
        redirect("/");
    }
    else
    {
        // else render form
        render("register_form.php", ["title" => "Register"]);
    }

?>
4

2 回答 2

0

您还可以使用简单的正则表达式来验证用户的电子邮件

if(preg_match('#^(.*)\@school\.edu$#', $_POST['email'])) {
    echo 'email is valid';
} else {
    echo 'this is not valid email!';
}
于 2012-12-08T14:18:57.293 回答
0

您可以结合使用substr()函数和strrpos()来获取电子邮件的最后一部分:

if(substr($email, strrpos($email, "@")) == "@school.edu") {
  //all good
}

完成此操作后,您可以通过电子邮件向他们发送一个指向所提供电子邮件的确认链接,以确保它不是伪造的。

于 2012-12-08T14:09:46.670 回答