NaiZuro
NaiZuro

Reputation: 11

Can't get $_SESSION['user'] to show / session not actually recorded?

I have to start of by saying that I'm fairly new to PHP and trying the best I can.

I've searched far and wide for a solution but as there are similar questions /answers, I haven't been able to solve my problem.

I have a fairly simple login screen / check as login.php and a secure.php (will show both files at the end of my post) where the user gets redirected to when username & password match the database.

When you press the login button while filling in a correct user/pass nothing happens, because the session logged in is aparently false and it just keeps looping login.php.

The rest as in not filled in all forms, wrong pass or user notices all work correctly so nothing wrong there.

So, how do I get my session as TRUE and show the logged in username on secure.php?

Login.php :

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="login screen" content="">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<title>TEST</title>
<link rel="stylesheet" href="css/style.css">

<?php

session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    if (isset($_POST['username']) && trim($_POST['username']) != '' && 
        isset($_POST['password']) && trim($_POST['password']) != '')
    {
        try 
        {
            $maxAttempts = 4;
            $attemptsTime = 10;

            $db = new PDO('mysql:host=localhost;dbname=users', 'root', '');
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $checkUsers = 
                "SELECT 
                    user_id
                FROM
                    users
                WHERE
                    username = :username
                AND
                    password = :password";
            $userStmt = $db->prepare($checkUsers);
            $userStmt->execute(array(
                                ':username' => $_POST['username'],
                                ':password' => $_POST['password'])
                                );
            $user = $userStmt->fetchAll();

            $checkTries =
                "SELECT
                    username
                FROM
                    loginfail
                WHERE
                    DateAndTime >= NOW() - INTERVAL :attemptsTime MINUTE
                AND
                    username = :username    
                GROUP BY
                    username, IP
                HAVING
                    (COUNT(username) = :maxAttempts)";
            $triesStmt = $db->prepare($checkTries);
            $triesStmt->execute(array(
                                ':username' => $_POST['username'],
                                ':attemptsTime' => $attemptsTime,
                                ':maxAttempts' => $maxAttempts
                                ));
            $tries = $triesStmt->fetchAll();

            if (count($user) == 1 && count($tries) == 0)
            {
                $_SESSION['user'] = array('user_id' => $user[0]['user_id'], 'IP' => $_SERVER['REMOTE_ADDR']);
                header('Location: secure.php');
                die;
            }
            else
            {
                $insertTry = 
                    "INSERT INTO
                        loginfail
                            (username, 
                            IP,
                            dateAndTime)
                    VALUES
                        (:username,
                        :IP,
                        NOW())";
                $insertStmt = $db->prepare($insertTry);
                $insertStmt->execute(array(
                                        ':username' => $_POST['username'],
                                        ':IP' => $_SERVER['REMOTE_ADDR']
                                        ));
                if(count($tries) > 0)
                {
                    header('Refresh: 3; url=login.php');
                    $message = 'To many login tries, try again in a couple of minutes.';
                }
                else
                {
                    header('Refresh: 3; url=login.php');
                    $message = 'Username or password not correct.';
                }
            }
        }
        catch (PDOException $e)
        {
            $message = $e->getMessage();
        }
        $db = NULL;
    }
    else
    {
        header('Refresh: 3; url=login.php');
        $message = 'Please fill in all required fields.';
    }
}
?>

<body>

    <?php
        if (isset($message))
        {
            echo $message;
        }
    ?>

    <form method="post" action="login.php" class="login">

    <p>
        <label for="username">User:</label>
        <input type="text" name="username" id="username">
    </p>

    <p>
        <label for="password">Password:</label>
        <input type="password" name="password" id="password">
    </p>

    <p class="login-submit">
        <button type="submit" class="login-button">Login</button>
    </p>

    </form>

</body>

Secure.php :

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="secure" content="">
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
<title>Secure</title>
<link rel="stylesheet" href="css/style.css">

<?php 

session_start(); 

if(!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] == false) 
{ 
    header('Location: login.php'); 
    exit(); 
}  
echo 'Welcome '.$_SESSION['user'].' and thanks for logging in.</center>'; 
?>

Upvotes: 0

Views: 157

Answers (4)

Joci93
Joci93

Reputation: 833

You don't have $_SESSION["logged_in"] .... you have $_SESSION['user']

Try this:

if(!isset($_SESSION['user']) || $_SESSION['user'] == false){ 
  header('Location: login.php'); 
   exit(); 
 } 
   echo 'Welcome '.$_SESSION['user'].' and thanks for logging in.</center>';

Upvotes: 1

Carlos M. Meyer
Carlos M. Meyer

Reputation: 446

You have to look at two points: - where is "session_start" placed - how you save you file

You must start sessions before you send any byte. So, "session_start()" should be placed at the beginning of your file. No HTML code, spaces or "intros" can be before yo start your PHP code where you start the SESSION.

Look at how you save your file too. It's not the same save it as "UTF-8" as "UTF-8 without BOM". With the first type you SESSION will not work.

Upvotes: 0

Bas
Bas

Reputation: 61

You did not set $_SESSION['logged_in']. So in secure.php it will redirect back to login.php. Set $_SESSION['logged_in'] to true before redirecting and it will work

Upvotes: 0

Superlocrian
Superlocrian

Reputation: 11

session_start(); must be before all output

<?php session_start(); ?>    

<meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="login screen" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
    <title>TEST</title>
    <link rel="stylesheet" href="css/style.css">

Upvotes: 0

Related Questions