检查可能不存在的会话变量

Check a sessions variable that may not exist

我有一个在用户登录时启动的会话,但是某些代码可能会被命中,询问可能尚不存在的会话变量,是否还有一种方法可以在此处检查变量,或者是否有其他方法关于它。

PHP 如果用户不是管理员,则运行隐藏框,但该检查可能在用户登录之前发生。我将如何检查会话变量值?

我曾尝试将隐藏框的代码移动到单独的页面,例如登录页面,但无济于事,顺便说一句,登录是一个弹出窗口,而不是另一个 window。

session_start();

$connect= new mysqli('localhost', 'root', '', 'login') or die("connection failure, please try again later");

$username= $_GET["username"] ?? '';
$password= $_GET["password"] ?? '';

echo "<br>","$username";

$getsalt="SELECT * FROM users WHERE uname='$username'";

$salt= $connect->query($getsalt);

$currentsalt = "";

while($row=$salt->fetch_assoc()) {
    $currentsalt = $row["salt"];
    $_SESSION["uname"] = $row["uname"];
    $_SESSION["id"] = $row["id"];
    echo'<br>', 'is admin ', $row['is_admin'];
    $_SESSION["is_admin"] = 1;
    if($row["is_admin"] == 1) {
        echo 'is  admin';
        $_SESSION["is_admin"] = 1;
    } else {
        echo 'is not admin';
    }
}
echo "<br>","$password";
echo "<br>", $currentsalt;

if($currentsalt == null) {
        echo "user doesnt exist";
} else {
$hashed= sha1($password.$currentsalt);

echo "<br>", $hashed;

$getaccount="SELECT * FROM users WHERE uname='$username' AND pass='$hashed'";

$result= $connect->query($getaccount);

if($result-> num_rows>0) {
    while($row=$result->fetch_assoc()) {
        echo "<br>","Admin name is: " . $row["uname"];
        header("Location: /index.php");
    }
} else {
    echo "<br>","sorry password was incorrect";
}
}

你可以尝试使用if(isset($_SESSION['name']) && $_SESSION['name'] )

此代码检查变量是否存在并具有一些值

Edit: Added a new answer based on the latest comments.

我会分两部分回答你的问题。

检查是否设置了会话变量。

您可以使用 empty()

检查变量是否存在
if (empty($_SESSION['is_admin'])) {
    // do the action if the currently logged in user is not an admin
} else {
    // do the action if an admin user is logged in
}

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

对所有受保护的页面执行登录检查。

建议在所有为登录用户保留的页面顶部添加登录检查。

您可以按如下方式添加登录检查。

创建一个名为 checkLogin()

的辅助函数
function checkLogin(){
    if (!empty($_SESSION['user_id'])) {
        return true;
    } else {
        header("Location: https://YOUR_LOGIN_PAGE_URL");
        die();
}

然后,在任何您想限制未经授权的用户访问该页面的地方,包括此 checkLogin() 功能。

确保您已将此函数添加到应用程序通用的文件中

这个问题已经解决了,虽然我不知道如何将它标记为已解决。关键是你必须在每个页面上使用 session_start(); 开始会话,感谢无效的 bot 和 Railson luna,现在它们中的任何一个都可以工作!

我已经修改了你在问题中给出的代码如下。

I have noticed some bad practices in your code and I have added comments on them. Please read them

<?php
session_start();
$connect= new mysqli('localhost', 'root', '', 'login') or die("connection failure, please try again later");

$username= $_GET["username"] ?? ''; // Username and password should not be passed as a part of the URL. Use POST instead
$password= $_GET["password"] ?? ''; // Username and password should not be passed as a part of the URL. Use POST instead


// Get the details of the user having the given Username
// Make the username field unique so that no two users can have the same username.

$getsalt="SELECT * FROM users WHERE uname='$username' LIMIT 1";
$userRow = $connect->query($getsalt)->fetch_assoc();

// No user found matching username
if (empty($userRow)) {
    // Handle the errors gracefully. Redirect the user back to the login page with an error message, instead of printing an error message.
    // echo "User doesn't exist.";
    // die();
    $_SESSION['loginError'] = "No users found"; 
    header('Location: login.php');
    die();

} else {
    // User found, now check the password

    // HERE YOU CAN AVOID AN UNNECESSARY DATABASE CALL.


    $salt = $userRow['salt'];
    $passwordHash = sha1($password . $salt);
    if ($userRow['pass'] === $passwordHash) {
        // password check succeeded. Let the user logged in
        $_SESSION['uname'] = $userRow['uname'];
        $_SESSION['id'] = $userRow['id'];
        if (!empty($userRow['is_admin'])) {
            $_SESSION['is_admin'] = 1;
        }
        header("Location: /index.php");
    } else {
        // Password check failed. Do not allow the user to logged in
        // Handle the errors gracefully. Redirect the user back to the login page with an error message
        // echo "Incorrect Password";
        // die();
        $_SESSION['loginError'] = "Incorrect Password"; 
        header('Location: login.php');
        die();
    }
}

在您的 login.php 中,添加以下代码以显示错误消息

<?php
session_start();
if (!empty($_SESSION['loginError'])) {
?>
<div class="error-message"><?php echo $_SESSION['loginError'];?> </div>
<?php 
unset($_SESSION['loginError'];// we do not need this error message anymore
} 
?>

// Rest of your login page code goes here...