0

I have used a hash encryption of the password for the user so in the login i check with password_verify if the passwords match and that part of the code seems to be working. And everything inside of the if statment besides something with the sessions. The header Location works but i just get sent back and in the errorlog it says; Undefined index: authorized in C:\xampp\htdocs\portfolio\admin.php on line 22. And authorized is the session im trying to create for checking if the user is logged in.

So my question is partly what I'm doing wrong and partly how a good way to work with sessions in an loginfunction is? My admin.php is supposed to only be accessed if the user is logged in. I will paste the important parts of the code below.

My login.php page:

In the top of the document:

// Error log  
ini_set('log_errors', 1);
ini_set('error_log', 'logs/error_log.txt');

//Session
session_start();
session_regenerate_id();

// Includes
include_once 'actions/login_action.php';
?>

In the body:

<div id="login">
    <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" autocomplete="off">
        <p><input type="text" name="user" placeholder="Username" maxlength="30" required/></p>
        <p><input type="password" name="pass" placeholder="Password" maxlength="30" required /></p>
        <input class="green" name="login" type="submit" value="Log In >>" />
    </form>
</div>

<?php
    }else{
        echo "You are already logged in.";
    }
?>

My login_action.php page:

The loop that fetch the result and checks the password:

            // Fetch the result
            while($stmt->fetch()) {
                $pass_crypt = $password;

                // Checking password & making sessions
                if (password_verify($pass, $pass_crypt) == $pass_crypt) {
                    $_SESSION['authorized'] = true;
                    $_SESSION['username'] = htmlspecialchars($user);

                    // Successful signin logs in logs/success_signin_log.txt
                    $successLog = fopen("logs/success_signin_log.txt", "ab");
                    $txt = 'Successful login preformed ' . $date . ' by ' . $user . "\r\n";
                    fwrite($successLog, $txt);
                    fclose($successLog);

                    // Sends to myplace.php
                    header("Location: admin.php");
                }else {
                    $user = "";
                    $_SESSION['authorized'] = false;
                    $errlogin = "Invalid login";
                    $error = "Login failed, please try again.";
                }
            }

My admin.php page:

In the top of the document:

// Error log  
ini_set('log_errors', 1);
ini_set('error_log', 'logs/error_log.txt');

// Session
session_start();
session_regenerate_id();

// If the session is not set your not logged in or empty user will be sent back to the login page.
if (!isset($_SESSION['authorized']) || $_SESSION['authorized'] == false) {
  header ("Location: login.php");
}

?>
2
  • I just skimmed through your question and saw the condition in your last snippet !isset($_SESSION['authorized']) && $_SESSION['authorized'] == false, which will / can never be true. Did you probably mean !isset($_SESSION['authorized']) || $_SESSION['authorized'] == false? Commented Jun 2, 2015 at 10:58
  • That works for the error, thanks, but somehow the session still seems to not exist. any clue what more i might have done wrong? @Havelock Commented Jun 2, 2015 at 11:23

1 Answer 1

1

This is just a logical error because of how you coded the if condition in your admin.php file

!isset($_SESSION['authorized']) && $_SESSION['authorized'] == false

The isset() method in PHP returns false if the index does not exist in the array. So in your case when !isset($_SESSION['authorized']) evaluates to true the other part of the AND condition still needs to be evaluated in order to execute the code inside the if-statement. The error you get appears at this moment because you use $_SESSION['authorized'] as part of your second condition and the key 'authorized' might not exist.

You need to rewrite the condition for example like:

!isset($_SESSION['authorized']) || $_SESSION['authorized'] == false

In this case this means that if the 'authorized' index does not exist your first part of the condition will evaluate to true and as true || whatever will always evaluate to true the second part does not need to be evaluated and you will not get the PHP error. The second part will only be evaluated when the first one evaluates to false which actually means the index exists so you will be fine anyway.

Of course you can build this condition in many other ways which might be easier to understand / read such as:

!isset($_SESSION['authorized']) || ( isset($_SESSION['authorized']) && $_SESSION['authorized'] == false)

Always when writting this kind of conditions try to keep in mind what you really want to cover. In this case:

  • Session key does not exist
  • Session key exists but the value is false

Then, build your Boolean expression step by step and finally try to reduce it by applying Boolean Algebra or simply by using tricks like the one I mentioned above: If PHP already assumes a condition evaluates to true or to false it will never finish evaluating the expression in order to faster.

Sign up to request clarification or add additional context in comments.

11 Comments

I tried a lot of different ways, but will try this, get back about it soon :)
I don't get any error now but I still get sent back to the login.php. Any clue what more might be wrong? Seems like the session somehow dosent exist, but I dont really now where i done wrong. @dncolomer
Have you tried quickly debugging your code to check what are the contents of $_SESSION right before the condition? If you are not familiar with debugging tools you can quickly use var_dump($_SESSION); to see what's inside. try inspecting the content of the array at different points in your code to see where the unexpected behavior actually occurs.
Im really bad at debugging so where should i try to put it? Because if I put it in the login_action.php it woun't show anywhere anyway? Or dose it show in the errorlog? I tried all i knew before writing here. Just know how to use echo for writing it out doh.
You can combine the var_dump call with a call to die() in order to stop the execution right after (var_dump($_SESSION);die;). This way you can quickly see the contents of the variable in the browser. Note that this is not generally a good practice in real-world development.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.