2012-04-23 220 views
1

這是代碼PHP登錄腳本重定向

<?php 

//Start session 
session_start(); 

//Then we retrieve the posted values for user and password. 
$username = $_POST['username']; 
$password = $_POST['password']; 

//Users defined in a SQLite database 
$db = new PDO("sqlite:/www/test.db"); 
$result = $db->query("SELECT COUNT(*) FROM users WHERE Username = '$username' AND Password = '$password'"); 

if ($result > 0) 
{ 
    //If user and pass match any of the defined users 
    $_SESSION['loggedin'] = true; 
    // close the database connection 
    unset($db); 
    header("Location: index.php"); 
}; 

//If the session variable is not true, exit to exit page. 
if(!$_SESSION['loggedin']) 
{ 
    // close the database connection 
    unset($db); 
    header("Location: login.html"); 
    exit; 
}; 

?> 

數據庫模式:

用戶名TEXT NOT NULL PRIMARY KEY UNIQUE,密碼文本

唯一的行數用戶名='admin'和密碼='admin'

任何想法爲什麼即使用戶名和密碼不在數據庫中,腳本爲什麼每次都將index重定向到index.php?

在此先感謝

+2

把一個exit();在header()後面停止進一步的執行。 – djot 2012-04-23 18:02:51

回答

4

$db->query會返回一個資源,如果沒有遇到錯誤。不是查詢的結果。因此,由於你的查詢執行得很好,你會得到一個始終大於0的資源句柄。這就是爲什麼它似乎每個人都成功登錄。

你需要得到你的查詢結果,並檢查是否COUNT(*)的值大於零(或等於1)。

+0

我認爲檢查'$ result> 0'就足夠了。 已經測試過這個查詢,並且知道它輸出1表示正確的值,0表示這些列中不存在的值。 – 1000Gbps 2012-04-23 18:17:50