2013-02-22 31 views
-3

這是我第一次使用SESSIONS登錄系統。 想知道,如果SQL注入安全嗎?我的代碼是否安全的SQL注入?簡單會話登錄

<?php 
$username = $_POST['username']; 
$password = $_POST['password']; 

if(isset($username, $password)) { 
    if(get_magic_quotes_gpc()) { 
     $ousername = stripslashes($username); 
     $uusername = mysql_real_escape_string(stripslashes($username)); 
     $opassword = stripslashes($_POST['password']); 
    } else { 
     $uusername = mysql_real_escape_string($username); 
     $opassword = $password; 
    } 
    $req = mysql_query('select password,id from users where username="'.$uusername.'"'); 
    $dn = mysql_fetch_array($req); 

    if($dn['password']==$opassword and mysql_num_rows($req)>0) 
    { 
     $form = false; 
     $_SESSION['username'] = $_POST['username']; 
     $_SESSION['userid'] = $dn['id'];   

    echo 'Logged in m8'; 
    } else { 
     $form = true; 
     $message = 'The username or password is incorrect.'; 
    } 
} else { 
    $form = true; 
} 
if($form) 
{ 
if(isset($message)) { 
    echo '<div class="message">'.$message.'</div>'; 
}   
?> 

,我在我的高分腳本之前得到一個SQL注入,所以我在想,如果我的簡單會話的登錄腳本有什麼,我40%有一個.. 什麼通常會導致SQL注入? 謝謝!

+0

你在哪裏調用'mysql_connect'? – 2013-02-22 03:06:23

+2

[SQL注入獲得mysql_real_escape_string()](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) – 2013-02-22 03:07:13

+0

它是。但是,使用[準備語句的PDO](http://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php)比mysql_保姆和手動轉義要容易得多。 – mario 2013-02-22 03:09:07

回答

2

雖然你的代碼是好的,保護您的想法是錯誤的
mysql_real_escape_string不從注射保護。它的格式字符串爲 只要你有你的字符串格式正確,他們是安全的。

當您嘗試使用相同的函數來格式化非字符串時(例如數字),問題就開始了。
它變得完全沒用,而且你的SQL很容易受到攻擊。

因此,您可以保留當前的代碼,但將來只要您需要使用另一個查詢部分 - 您需要對其進行不同的格式化。這裏有一套完整的規則:In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?

而且當然不要逃脫密碼!如果我有一個像wef5623'sdf的密碼 - 它永遠不會讓我進來!順便說一句,我不知道爲什麼你只用一個值來使用很多變量 - $ _POST ['username'],$ username,$ uusername,$ ousername - 這是什麼?

+0

+1 this answer is a informative a nd有意義... – 2013-02-22 05:44:30

-4

我會改變 $opassword = $password;

$opassword = mysql_real_escape_string($password); 

SQL注入可以通過密碼字段來實現了。

+0

我試過這個,謝謝! – 2013-02-22 03:41:49

+0

他們在SQL中沒有使用密碼,所以沒有通過密碼字段進行SQL注入 – 2013-02-22 05:09:45

+0

-1當然..同意(@YourCommonSense)我不認爲任何人在密碼不使用計劃文本不是嗎?我不知道如何使用SQL注入['sha1(''或'1'='1'/*'「);'](http://codepad.viper-7.com/KRsckw) – 2013-02-22 05:51:04