繁体   English   中英

PHP和MySQL:防止攻击-这些功能之间有何不同? [重复]

[英]PHP & MySQL: Preventing attacks - What's the different between these functions? [duplicate]

这个问题已经在这里有了答案:

我一直在研究一些用于登录数据库的示例代码,并且作者提供了两个功能,用于使输入的数据对数据库安全,而很少解释为何在何处使用。 我试图弄清楚它是否是多余的,以及是否根本不使用它们中的一个,因为它看起来很多...嗯...它的功能更轻。

这是第一个:

/*
Sanitize() function removes any potential threat from the
data submitted. Prevents email injections or any other hacker attempts.
if $remove_nl is true, newline chracters are removed from the input.
*/
function Sanitize($str,$remove_nl=true)
{
    $str = StripSlashes($str);

    if($remove_nl)
    {
        $injections = array('/(\n+)/i',
            '/(\r+)/i',
            '/(\t+)/i',
            '/(%0A+)/i',
            '/(%0D+)/i',
            '/(%08+)/i',
            '/(%09+)/i'
            );
        $str = preg_replace($injections,'',$str);
    }

    return $str;
}    
function StripSlashes($str)
{
    if(get_magic_quotes_gpc())
    {
        $str = stripslashes($str);
    }
    return $str;
}

现在是第二个:

/* No explanation whatsoever... */
function SanitizeForSQL($str)
{
    if( function_exists( "mysqli_real_escape_string" ) )
    {
          $ret_str = mysqli_real_escape_string($connection, $str);
    }
    else
    {
          $ret_str = addslashes( $str );
    }
    return $ret_str;
}

第一个代码(似乎更有用)看起来像在将发布的表单字段收集到数组中时仅使用了一次:

function CollectRegistrationSubmission(&$formvars)
{
    $formvars['Email'] = Sanitize($_POST['Email']);
}

第二种几乎在任何将任何东西放入数据库的表字段中或从SESSION数据中提取时都被使用,例如:

    $qry = "SELECT * FROM sessions WHERE Email='".SanitizeForSQL($Email)."'";

    /* or */

    $Email = SanitizeForSQL($_SESSION['email_of_user']);

我主要担心的是这似乎是多余的,但这也许是因为我不理解。 真的有理由要同时做这两项吗?

    $formvars['Email'] = Sanitize($_POST['Email']);

    $qry = "SELECT * FROM sessions WHERE Email='".SanitizeForSQL($formvars['Email'])."'";

所以,

有什么不同?

我应该只使用其中之一吗?

我应该在这些地方之一或全部都使用其他东西吗?

感谢您对此有何见解!

IMO而不是使用特定的数据库驱动程序MySQLi,最好使用数据库抽象层。 您可以使用PDO(PHP数据对象)。

<?php
/* Connect to a MySQL database using driver invocation */
$pdo = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $pdo = new PDO($dsn, $user, $password);
    $stmt = $pdo->prepare('SELECT * FROM sessions WHERE email = :email');

    // PDO will take care sanitizing the input so you do not need
    // to manually quote the parameters
    $stmt->execute([':email' => $_POST['email']]);

    $result = $stmt->fetchAll();
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

进一步阅读: http : //php.net/manual/en/book.pdo.php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM