i hate php
i hate php

Reputation: 1

Check a sessions variable that may not exist

I have a session that starts if a user logs in, but certain code may be hit asking for session variables that may not exist yet, is there still a way of checking the variable here or is there another way to go about it.

PHP runs hiding a box, if a user isn't an admin, but that check could happen before the user logs in. how would i go about checking that session variables value?

I have tried moving the code to hide the box to a seperate page, like the log in page, but to no avail, the log in is a popup by the way not another 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";
}
}

Upvotes: 0

Views: 3249

Answers (4)

ash__939
ash__939

Reputation: 1599

I have modified your code given in the question as below.

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();
    }
}

In your login.php, add the following code to show an error message

<?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...

Upvotes: 0

ash__939
ash__939

Reputation: 1599

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

I will answer your question in two parts.

Check if a session variable is set or not.

You can check if a variable exists by using 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.

Perform a login check on all protected pages.

It is recommended to add a login check at the top of all pages those are reserved for logged in users.

You can add a login check as follows.

Create a helper function called checkLogin()

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

Then, wherever you want to restrict unauthorised users accessing the page, include this checkLogin() function.

Be sure you have added this function in a file common to your application

Upvotes: 1

i hate php
i hate php

Reputation: 1

This question is solved, although i dont know how to mark it as solved. the key was you have to start the session on every page with session_start();, thanks to invalid bot and Railson luna, either of those will now work!

Upvotes: 0

Railson Luna
Railson Luna

Reputation: 65

You can try to use if(isset($_SESSION['name']) && $_SESSION['name'] )

this code check if variable existe and have some value

Upvotes: 0

Related Questions