2013-02-22 102 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