简单的登录会话php

时间:2013-06-03 04:25:04

标签: php session login phpmyadmin

无法让我的会话启动并运行。在过去的几个小时里,我一直在寻找我的代码,我看不出它有什么问题。我遇到的问题是,每当我输入用户名和密码时,它只是重定向到登录页面,当它应该显示securepage.php时再次输入信息..

这是我的代码:

loginproc.php页面 - 此页面逐步执行if语句并直接进入else

<?php

// Inialize session
session_start();

// Include database connection settings
include('../../model/database.php');

// Retrieve username and password from database according to user's input
$login = mysql_query("SELECT * FROM user WHERE (username = '" . mysql_real_escape_string($_POST['username']) . "') and (password = '" . mysql_real_escape_string($_POST['password']) . "')");

// Check username and password match
if (mysql_num_rows($login) == 1) {
// Set username session variable
$_SESSION['username'] = $_POST['username'];
// Jump to secured page
header('Location: securedpage.php');
}
else {
// Jump to login page
header('Location: index.php');
}

?>

securedpage.php页面

<?php

// Inialize session
session_start();

// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['username'])) {
header('Location: index.php');
}

?>
<html>

<head>
<title>Secured Page</title>
</head>

<body>

<p>This is secured page with session: <b><?php echo $_SESSION['username']; ?></b>
<br>You can put your restricted information here.</p>
<p><a href="logout.php">Logout</a></p>

</body>

</html>

database.php页面

<?php
$dsn = 'mysql:host=localhost;dbname=sports_db';
$username = '';
$password = '';
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);

try {
    $db = new PDO($dsn, $username, $password, $options);
} catch (PDOException $e) {
    $error_message = $e->getMessage();
    include 'errors/db_error_connect.php';
    exit;
}

function display_db_error($error_message) {
    global $app_path;
    include 'errors/db_error.php';
    exit;
}
?>

3 个答案:

答案 0 :(得分:8)

您无法混合PDO和mysql ..您正在PDO创建查询并使用mysql_* 尝试将代码更改为

<?php

// Inialize session
session_start();

// Include database connection settings
include('../../model/database.php');

// Retrieve username and password from database according to user's input
$stmt = $db->prepare("SELECT * FROM user WHERE (`username` = :username) and (`password` = :password)");

$result = $stmt->execute(array(':username'=>$_POST['username'],':password'=>$_POST['password']));
$num_rows = $stmt->rowCount();
// Check username and password match
if ( $num_rows > 0) {
// Set username session variable
$_SESSION['username'] = $_POST['username'];
// Jump to secured page
header('Location: securedpage.php');
}
else {
// Jump to login page
header('Location: index.php');
}

?>

请参阅reference

答案 1 :(得分:0)

问题可能在于:

if (mysql_num_rows($login) == 1) {

如果要检查整数1,请使用三重等式。但最有可能的是登录/传递失败。

而且:

$_SESSION['username'] = $_POST['username'];
即使你得到有效的答复,

也是不好的做法。

答案 2 :(得分:0)

我有一个建议:

1)不要将用户给定的数据直接存储到会话变量中。

2)首先检查表中是否存在用户凭证,获取相应的行,然后将获取的数据存储在会话变量中。