doufeng1249 2015-03-12 15:52
浏览 335
已采纳

为什么PHP if(!$ _ SESSION ['username'])返回false

I have been coding a basic PHP Login script just for testing purposes.

<?php
require 'config.php';
require 'connect.php';

// username and password sent from form 
$tbl_name = 'users';
$username=$_POST['username']; 
$password=$_POST['password']; 

// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result = mysqli_query($conn, $sql);

// Mysql_num_row is counting table row
$count = mysqli_num_rows($result);

// If result matched $username and $password, table row must be 1 row
if($count == 1)
{
// Register $username, $password and redirect to file "login_success.php"
$_SESSION["username"];
$_SESSION["password"]; 
header("location:../../home.php");
}
else {
echo "Wrong Username or Password";
}
?>

I am able to get through this with no problem, but when it redirects to home.php, here is the code I have to check if session is not registered.

<?php
session_start();
if (!$_SESSION['username']) {
header("location:../../index.php");
}
?>

From what I understand, this is supposed to check if the user is not logged in, however when I login it still redirects me to index.php. How can I make sure the session is registered and nothing happens (i.e. I stay on home.php with no redirect, but I'm still logged in.)

  • 写回答

2条回答 默认 最新

  • dongxi0523 2015-03-12 15:57
    关注

    You need to save save something in session variable

    if($count == 1)
    {
    // Register $username, $password and redirect to file "login_success.php"
    $_SESSION["username"]=$username;
    $_SESSION["password"]; //Don't do this its a bad practice.
    header("location:../../home.php");
    }
    else {
    echo "Wrong Username or Password";
    }
    

    Also don't forget to start session before using session variable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀