0

我制作了一个运行良好的登录脚本,除了即使用户名和密码不正确它也会登录。

这是代码:

<?php
//SQL ENTRY
$username_db = "root";
$password_db = "";
$host = "127.0.0.1";
$db = "teach_login";

//Requested
$usern = $_POST['username'];
$pw = $_POST['password'];

//Make it safe
$usern = htmlspecialchars($usern);
$pw = htmlspecialchars($pw);
$pwmd5 = md5($pw);

//SQL SETTINGS  
$db_handle = mysql_connect($host, $username_db, $password_db);
$db_open = mysql_select_db($db, $db_handle);
echo $db_open."<br />";
if ($db_open){
    $SQL = "SELECT `username` FROM userpassword WHERE (username = '$usern' && password = '$pwmd5') ";
    $result = mysql_query($SQL);
    echo $result."<br />";;
    if ($result >= 1){
        $SQL_name = "SELECT * FROM `userpassword` WHERE (username = '$usern') ";
        $result_new = mysql_query($SQL_name);
        while($row = mysql_fetch_assoc($result_new)){
            $name = $row['full_name'];
            echo $name;
            echo "<br />";
            echo $row['password']."<br>";
            $SQL = "UPDATE `userpassword` SET `logged_in`=[1] WHERE `username` = '$usern' ";
            $result = mysql_query($SQL);
            if ($result > 0){
                mysql_close($db_handle);
            }else{
                echo "Data Not written";
            }
        }
        /*echo $result_new."<br />";            
        echo $result_name_array."<br />";
        $name = $result_name_array[1];
        echo $name."<br />";
        session_start();
        $_SESSION['login_name'] = $name;
        $_SESSION['login'] = 1;
        mysql_close($db_handle);
        //header ("location: teach_home.php");
        */
    }else{

        echo "Cannot Login";
        //header ("location: teach_login.php");
        mysql_close($db_handle);
    }

}else {
    echo ('DATABASE NOT FOUND');
    mysql_close($db_handle);
}
?>

输出是这个 SQL ENTRY:

1<br>
Resource id #4<br>
Salik Sadruddin<br>
14918756cc99b9e6ce69f4c943680efc<br>
Data Not written<br>
4

2 回答 2

1

这就是缺陷所在:

$result = mysql_query($SQL);
if ($result >= 1){
    // …
}

的返回值mysql_query不是所选行数,而是:

对于 SELECT、SHOW、DESCRIBE、EXPLAIN 和其他返回结果集mysql_query()的语句,成功时返回资源,错误时返回 FALSE。

在您的情况下,查询可能会成功,但不会选择任何记录,但是mysql_query会返回满足表达式的资源$result >= 1

要解决此问题,请使用mysql_num_rows获取选定行数:

if ($result && mysql_num_rows($result) === 1){
    // …
}

还可以考虑使用MySQLiPDO_MYSQL代替标准 MySQL 扩展。您还应该阅读有关SQL 注入的信息,因为您当前的代码很容易受到攻击。

于 2012-06-10T11:24:33.240 回答
0

对于更新,如果 UPDATE 语句成功 $result 会给你 0。对于插入它会给你 1

$SQL = "UPDATE `userpassword` SET `logged_in`=[1] WHERE `username` = '$usern' ";
        $result = mysql_query($SQL);
        if ($result == 0){
            echo "Data Updated";
            mysql_close($db_handle);
        }else{
            echo "Data Not written";
        }
于 2012-06-10T11:24:10.437 回答