doufeng1249 2015-03-12 07: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 07: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部