我开发了这组2个脚本,以便使用$ _SESSION变量来检查用户是否已登录。我没有使用cookie,因为我还不想进入那个“jazz”。
这是login.php
require 'host.php'; // Connection to database
$message = '';
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ((!$username) || (!$password)) {
$message ='Preencha todos os campos.';
} else{
$username = preg_replace("#[^0-9a-z]#i","",$username);
$password = sha1($password);
$sql = "SELECT * FROM utilizadores WHERE nome_utilizador='$username' AND palavra_chave='$password' LIMIT 1";
$query = mysql_query($sql) or die();
if (mysql_num_rows($query) == 1) {
// Logged in stuff
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
while ($consulta = mysql_fetch_array($query)) {
$id = $consulta['id_utilizador']; // ID of username.
}
$_SESSION['id'] = $id;
$message = '<a href="calendario.php">Clique aqui para ir para o calendário.</a>'; // Message that is shown to redirect to another page.
} else{
$message = 'Os dados que inseriu estão incorrectos!'; // Data inserted is incorrect.
}
}
}
这是检查用户是否已登录的文件
session_start();
include 'host.php';
if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
$password = $_SESSION['password'];
//Verificar se o user existe.
$sql = "SELECT * FROM utilizadores WHERE id_utilizador='$id' AND palavra_chave='$password' LIMIT 1";
$query = mysql_query($sql) or die('Could not connect.');
if (mysql_num_rows($query) > 0) {
header('Location: logout.php');
} else{
// Logged in stuff
$logged = 1;
}
} else{
$logged = 0;
}
我想要检查会话是否包含每个页面中的文件,并检查$ logged == 0.
但它不会在页面之间存储会话数据。
希望你能帮助我!
谢谢!
答案 0 :(得分:1)
你的id变量在while循环中,不能在while循环外读取。这就是为什么会话没有存储
尝试在while循环
之前定义id变量 $id = "";
while ($consulta = mysql_fetch_array($query)) {
......
你可以尝试在while循环之后回显一些东西 像那样
echo $id ;
答案 1 :(得分:0)
我终于解决了这个问题!
我添加的所有内容是更改verify_session.php,并在mysql_num_rows()中将其设置为== 0,而不是&gt; 0
感谢所有帮助人员!