FILTER_VALIDATE_EMAIL

时间:2012-02-22 15:43:43

标签: php forms email

我知道之前已经讨论过这个问题,但是自从2010年末这篇文章以及围绕那个时候提出问题的其他讨论 - Does FILTER_VALIDATE_EMAIL make a string safe for insertion in database? - 我尝试了一些描述的情况,例如使用单引号和`我在使用FILTER_VALIDATE_EMAIL的电子邮件表单中的字符,并阻止它们进入数据库。

最近发布的PHP修复了之前的问题,是否安全?

我很想也使用mysql_real_escape_string(),大概两个函数可以并行使用而不会有任何冲突?

以下是我用来将地址放入数据库的邮件列表代码

    <?php
// connects the database access information this file
include("mailing_list_include.php");

// the following code relates to mailing list signups only
if (($_POST) && ($_POST["action"] == "unsub")) {
// trying to ubsubscribe; validate email addresses
if ($_POST["email"] == "") {
    header("Location: mailing_list_remove.php");
    exit;

} else {
    // connect to database
    doDB();

    // filtering out anything that isn't an email address
    if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL)  == TRUE) {
        echo '';
    } else {
        echo 'Invalid Email Address';
        exit;
    }

    // check that email is in the database
    emailChecker($_POST["email"]);

    // get number of results and do action
    if (mysqli_num_rows($check_res) < 1) {
        // free result
        mysqli_free_result($check_res);

        // print failure message
        $display_block = "We couldn't find ".$_POST["email"].". No action has therefore been taken.";

    } else {
        // get value of ID from result
        while ($row = mysqli_fetch_array($check_res)) {
            $id = $row["id"];
        }

        // unsubscribe the address
        $del_sql =  "DELETE FROM subscribers
                    WHERE id = '".$id."'";
        $del_res =  mysqli_query($mysqli, $del_sql)
                    or die(mysql_error($mysqli));
        $display_block = " Your email address, ".$_POST["email"].", is unsubscribed!";
    }
    mysqli_close($mysqli);
}
}
?>
<html>
<?php echo "$display_block";?>
</html>

1 个答案:

答案 0 :(得分:3)

filter_var标志FILTER_VALIDATE_EMAIL将执行它所说的=验证值作为电子邮件,这意味着如果它不是电子邮件,它将返回false。

您可能正在寻找FILTER_SANITIZE_EMAIL将删除所有字符,除了字母,数字和!#$%&amp;'* + - / =?^ _`{|}〜@。[])

FILTER_SANITIZE_STRING将剥离标签,可选择剥离或编码特殊字符。

我不推荐w3schools它有一个filter_var标志列表http://www.w3schools.com/php/php_ref_filter.asp

正如其他人所说,使用PDO准备的查询是安全的,你可以在这里找到一个很棒的pdo示例:http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#10这将解释一些事情,还有一个简单的pdo CRUD(创建检索更新删除)这里上课:http://www.phpro.org/classes/PDO-CRUD.html

祝你好运......