2012-04-23 222 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