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

?>
Sanna Bergström
  • 95
  • 1
  • 3
  • 12
  • 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`? – Havelock Jun 02 '15 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 – Sanna Bergström Jun 02 '15 at 11:23

1 Answers1

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.

dncolomer
  • 93
  • 1
  • 7
  • I tried a lot of different ways, but will try this, get back about it soon :) – Sanna Bergström Jun 02 '15 at 11:14
  • 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 – Sanna Bergström Jun 02 '15 at 11:17
  • 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. – dncolomer Jun 02 '15 at 11:30
  • 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. – Sanna Bergström Jun 02 '15 at 11:35
  • 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. – dncolomer Jun 02 '15 at 11:41
  • I tried a bit, the array seems empty on admin.php but if I didnt use the code that redirected to admin.php and used the var_dump on the login.php it seems to exist; array(2) { ["authorized"]=> bool(true) ["username"]=> string(14) "sannabergstrom" } . So something is wrong after the header (Location: admin.php) – Sanna Bergström Jun 02 '15 at 11:44
  • ah ok, smart, die i used but in other ways/places. – Sanna Bergström Jun 02 '15 at 11:45
  • It seems like the session dosent exist after you get sent to admin.php with the code: header("Location: admin.php"); But I cant really see why, isn't a session supposed to exist over all the sides? Or is it something I'm missing for it to do? – Sanna Bergström Jun 02 '15 at 11:49
  • Then I think I can point you to some similar questions where they seem to already solve this problem: http://stackoverflow.com/questions/17242346/php-session-lost-after-redirect If this solves it please don't forget to mark my answer as correct ;) – dncolomer Jun 02 '15 at 11:51
  • I will check it out! Thanks for all the help, will defently mark your answer if it solves it :) Hope you have seen that I voted the answer up at least for the moment ;). – Sanna Bergström Jun 02 '15 at 11:59
  • The sulotion was super simple.. kill me now xD. this solved it: header("Location: https://localhost/portfolio/admin.php"); So using the full path insted and using exit(); after... Thank you for all your help @dncolomer Will accept your answer :) – Sanna Bergström Jun 02 '15 at 12:22