2011-06-01 37 views
1

從php開始,我寫了一個基本的身份驗證腳本,如果在用戶表「test」中存在userid(由用戶提供),則在mysql服務器上打印出數據庫列表。數據庫。簡單的身份驗證腳本在PHP不工作

問題是,即使數據庫中不存在userid,該腳本也會輸出數據庫列表。我不確定腳本有什麼問題。請查看腳本,並幫助我瞭解爲什麼數據庫列表正在輸出,即使用戶標識不存在於數據庫中。這裏是腳本:

<?php 

if(isset($_POST['submitted'])) 
{ 
    $userid=$_POST['userid']; 
    $userpassword=$_POST['userpassword']; 
    $link_id=mysql_connect("localhost","root","pass"); 
    $result_db_list=mysql_list_dbs($link_id); 
    mysql_select_db("test",$link_id); 
    if(!($result_ptr=mysql_query("Select userid from user where Userid='$userid'",$link_id))) die ("Please enter correct userid"); 
    while($test=mysql_fetch_row($result_db_list)) 
     { 
     echo $test[0]."<br>"; 
     } 

} 
else 
{ 
?> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Authentication Script</title> 
<style type="text/css" > 
    #header{ 
    padding-top:0px; 
    margin:0px; 
    background-color:#CCCCCC; 
    } 
    .container{ 
    width:950px; 
    margin:0 auto; 
    border:1px solid red; 
    } 
.authbox { 
padding-top:100px; 
margin:0 auto; 
} 
    #footer{ 
    background-color:#666666; 
    color:white; 
} 
</style> 
</head> 

<body> 
<div id="header"> 

<div class="container"> 

<form action="authentication script.php" method="post"> 
<div class="authbox">UserName: <input type="text" name="userid" /><br/> 
Password: <input type="password" name="userpassword" /><br/> 
<input type="hidden" name="submitted" value="true" /> 
<input type="submit" value="Submit" /> 
</div> 
</form> 


</div> 

</div> 

<div id="footer"> 
Copywright 2010 NT Technologies. 
</div> 

</body> 
</html> 

<?php 
} 
?> 

謝謝 rseni。

+0

重新檢查你的sql查詢,你爲什麼不檢查用戶名和密碼? – 2011-06-01 15:46:40

+1

您的腳本容易受到SQL注入攻擊:http://en.wikipedia.org/wiki/SQL_injection – igorw 2011-06-01 15:47:40

+0

不一定與您的問題相關,但您不應在SQL語句中使用變量。如果可能的話,使用MySQLi(http://us3.php.net/manual/en/book.mysqli.php)和語句。如果不可用,請確保使用諸如「mysql_real_escape_string」(http://us3.php.net/manual/en/function.mysql-real-escape-string.php)之類的函數。上面的腳本容易受到SQL注入的影響。我意識到這可能是一個測試腳本,但最好養成使用這些方法的習慣。 – Rob 2011-06-01 15:50:17

回答

3

您的腳本中充滿錯誤。 (我希望至少你有magic_quotes on否則你是非常大的問題。請注意,你無論如何都應該避免magic_quotes的,並使用預處理語句)

這是發生因爲

if(!($result_ptr=mysql_query("Select userid from user where Userid='$userid'",$link_id))) 
    die ("Please enter correct userid"); 

這查詢不返回FALSE如果它不會選擇任何東西。

您應將其更改爲:

$result = mysql_query("SELECT COUNT(*) as countUser [etc]"); 
$r = mysql_fetch_assoc($result); 
if ($r['countUser']==0) 
    die('Denied'); 
1

APPU - 職場英語對話是正確的。查看php.net上關於mysql_query函數的文檔 - 您將看到它在成功時返回資源標識符,並在錯誤時返回FALSE。這裏的錯誤並不意味着沒有行返回 - 而是一個錯誤,例如您嘗試對不存在的表運行此查詢。

+3

感謝支持,但如果您將它作爲評論發佈,您的答案會更好:) – dynamic 2011-06-01 15:59:21