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条)

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?