TwinAxe96
TwinAxe96

Reputation: 139

PHP remember me functionality works after pressing log in

Hello i have encountered a problem implementing a remember me functionality in my test site. Currently i am trying to store the remember_me in a cookie that is set to expire 1 month from now. The idea is that when logging in if the user presses the remember me button he should stay logged in after he closes the browser and destroys the session and if he did not press the checkbox he should be logged out when the browser is closed (session destroyed). Currently it works, but only when the user presses the login button in the navbar (he skips the form and gets redirected to profil). What i want is the user to see the navbar that corresponds to a logged in user when he opens the index page without having to press log in. connect.php file:

<?php
ini_set('session.cookie_lifetime', 0);
session_start();

//Our MySQL user account.
define('MYSQL_USER', 'root');

//Our MySQL password.
define('MYSQL_PASSWORD', '');

//The server that MySQL is located on.
define('MYSQL_HOST', 'localhost');

//The name of our database.
define('MYSQL_DATABASE', 'qh_beer_shop');

/**
 * PDO options / configuration details.
 * I'm going to set the error mode to "Exceptions".
 * I'm also going to turn off emulated prepared statements.
 */
$pdoOptions = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false
);

/**
 * Connect to MySQL and instantiate the PDO object.
 */
$pdo = new PDO(
    "mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE, //DSN
    MYSQL_USER, //Username
    MYSQL_PASSWORD, //Password
     $pdoOptions //Options
);
$pdo->query('SET NAMES utf8');

login.php:

<?php
require_once 'connect.php';
if((isset($_SESSION['user']) AND trim( $_SESSION['user'] ) != "") OR ( isset($_COOKIE['remember_me']) AND trim($_COOKIE['remember_me'] ) != "" ) ) {
    if( isset($_COOKIE['remember_me']) AND trim($_COOKIE['remember_me'] ) != "" ) {
        $_SESSION['user']  = $_COOKIE['remember_me'];
    }
    header('Location: profile.php');
    exit;
}
$error = '';

try {
    if (isset($_POST['login'])) {

        $username = $_POST['username'];
        $password = $_POST['password'];

        //Retrieve the field values from our registration form.
        // $username = !empty($_POST['username']) ? trim($_POST['username']) : null;
        // $password = !empty($_POST['password']) ? trim($_POST['password']) : null;


//Construct the SQL statement and prepare it.
        $sql = "SELECT
              id AS id,
              username AS username,
              password AS password,
              email AS email,
              phone AS phone,
              address AS address,
              first_name AS first_name,
              last_name AS last_name,
              age AS age            
          FROM
              users
          WHERE
               username = ?
           ";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$username]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        $passwordHash = $user['password'];
        if (!password_verify($password, $passwordHash)) {
            setcookie('remember_me', '', time() - 100000);
            throw new Exception("Wrong username or password!");
        }
        else {
            if(isset($_POST['remember'])) {
                $month = time() + ( ( 3600 * 24 ) * 30 );
                setcookie('remember_me', $_POST['username'], $month);
            }
            else {
                $past = time() - 100;
                setcookie('remember_me', '', $past);
            }

            $hour = time() + 3600;
            setcookie('ID_my_site', $_POST['username'], $hour);

            $_SESSION['id'] = $user['id'];
            $_SESSION['user'] = $user['username'];
            header('Location: profile.php'); exit();
        }
//
//        $_SESSION['id'] = '';
//        $_SESSION['user'] = '';
//        header('Location: login.php');
//        exit;

    }
} catch (Exception $exception) {
    $error = $exception->getMessage();
}

?>

And here is the navbar that gets loaded in every page:

<?php
require_once 'connect.php'; ?>

<h1 style="width:50%; margin:0 auto; font-size: 50px; font-family: 'Raleway', sans-serif; color: black; font-weight: bold;">Quality House Beer</h1>
<nav>
    <a href="index.php"><img src="images/logoNew_bubbles.png"></a>
    <ul>
        <?php if (!isset($_SESSION['user'])): ?>
            <li><a id="home" href="index.php"><i class="fa fa-home"></i> HOME</a></li>
            <li><a id="catalog" href="catalog.php"><i class="fa fa-list"></i> CATALOG</a></li>
            <li><a id="about" href="about.php"><i class="fa fa-pencil"></i> ABOUT</a></li>
            <li><a id="register" href="register.php"><i class="fa fa-user"></i> REGISTER</a></li>
            <li><a id="login" href="login.php"><i class="fa fa-sign-in"></i> LOGIN</a></li>
            <li><a id="faq" href="faq.php"><i class="fa fa-question"></i> FAQ</a></li>
            <li><a href="#"><i class="fa fa-search"></i> <input
                            style="box-sizing: border-box; border: 2px solid; border-radius: 15px; height: 40px;"
                            type="text" placeholder=" Search..." name="search"></a></li>

        <?php elseif (isset($_SESSION['user']) && $_SESSION['user'] == 'admin'): ?>
            <li><a id="home" href="index.php"><i class="fa fa-home"></i> HOME</a></li>
            <li><a id="catalog" href="catalog.php"><i class="fa fa-list"></i> CATALOG</a></li>

            <li><a id="addBeer" href="create.php"><i class="fa fa-beer"></i> Add Beer</a></li>
            <li><a id="settings" href="addBeer.php"><i class="fa fa-beer"></i> SETTINGS</a></li>
            <li><a id="logout" href="logout.php"><i class="fa fa-sign-out"></i> LOGOUT</a></li>
            <li><a href="#"><i class="fa fa-search"></i> <input
                            style="box-sizing: border-box; border: 2px solid; border-radius: 15px; height: 40px;width: 220px;"
                            type="text" placeholder=" Search..." name="search"></a></li>
            <li><a id="profile" href="profile.php"><i class="fa fa-user"></i> <?= $_SESSION['user'] ?></a></li>
        <?php else :; ?>
            <li><a id="home" href="index.php"><i class="fa fa-home"></i> HOME</a></li>
            <li><a id="catalog" href="catalog.php"><i class="fa fa-list"></i> CATALOG</a></li>
            <li><a id="about" href="about.php"><i class="fa fa-pencil"></i> ABOUT</a></li>
            <li><a id="basket" href="basket.php"><i class="fa fa-beer"></i> BASKET</a></li>
            <li><a id="faq" href="faq.php"><i class="fa fa-question"></i> FAQ</a></li>
            <li><a id="logout" href="logout.php"><i class="fa fa-sign-out"></i> LOGOUT</a></li>
            <li><a href="#"><i class="fa fa-search"></i> <input
                            style="box-sizing: border-box; border: 2px solid; border-radius: 15px; height: 40px;width: 300px;"
                            type="text" placeholder=" Search..." name="search"></a></li>
            <li><a id="profile" href="profile.php"><i class="fa fa-user"></i> <?= $_SESSION['user'] ?></a></li>
        <?php endif; ?>
    </ul>
</nav>

Upvotes: 1

Views: 891

Answers (1)

Karlo Kokkak
Karlo Kokkak

Reputation: 3714

The navbar code is not checking if remember cookie is set. That's why even if you are logged in via the cookie, the page renders you're not.

Add to the navbar code the below code. Add it just after require_once 'connect.php';

if( isset($_COOKIE['remember_me']) AND trim($_COOKIE['remember_me'] ) != "" ) {
    $_SESSION['user']  = $_COOKIE['remember_me'];
}

Also in navbar code, to treat empty $_SESSION['user'] as not logged:

Replace:

<?php if (!isset($_SESSION['user'])): ?>

With:

<?php if (!isset($_SESSION['user']) OR trim( $_SESSION['user'] ) == ""): ?>

New Code:

<?php
require_once 'connect.php'; 

    if( isset($_COOKIE['remember_me']) AND trim($_COOKIE['remember_me'] ) != "" ) {
        $_SESSION['user']  = $_COOKIE['remember_me'];
    }
?>

<h1 style="width:50%; margin:0 auto; font-size: 50px; font-family: 'Raleway', sans-serif; color: black; font-weight: bold;">Quality House Beer</h1>
<nav>
    <a href="index.php"><img src="images/logoNew_bubbles.png"></a>
    <ul>
        <?php if (!isset($_SESSION['user']) OR trim( $_SESSION['user'] ) == ""): ?>
            <li><a id="home" href="index.php"><i class="fa fa-home"></i> HOME</a></li>
            <li><a id="catalog" href="catalog.php"><i class="fa fa-list"></i> CATALOG</a></li>
            <li><a id="about" href="about.php"><i class="fa fa-pencil"></i> ABOUT</a></li>
            <li><a id="register" href="register.php"><i class="fa fa-user"></i> REGISTER</a></li>
            <li><a id="login" href="login.php"><i class="fa fa-sign-in"></i> LOGIN</a></li>
            <li><a id="faq" href="faq.php"><i class="fa fa-question"></i> FAQ</a></li>
            <li><a href="#"><i class="fa fa-search"></i> <input
                            style="box-sizing: border-box; border: 2px solid; border-radius: 15px; height: 40px;"
                            type="text" placeholder=" Search..." name="search"></a></li>

        <?php elseif (isset($_SESSION['user']) && $_SESSION['user'] == 'admin'): ?>
            <li><a id="home" href="index.php"><i class="fa fa-home"></i> HOME</a></li>
            <li><a id="catalog" href="catalog.php"><i class="fa fa-list"></i> CATALOG</a></li>

            <li><a id="addBeer" href="create.php"><i class="fa fa-beer"></i> Add Beer</a></li>
            <li><a id="settings" href="addBeer.php"><i class="fa fa-beer"></i> SETTINGS</a></li>
            <li><a id="logout" href="logout.php"><i class="fa fa-sign-out"></i> LOGOUT</a></li>
            <li><a href="#"><i class="fa fa-search"></i> <input
                            style="box-sizing: border-box; border: 2px solid; border-radius: 15px; height: 40px;width: 220px;"
                            type="text" placeholder=" Search..." name="search"></a></li>
            <li><a id="profile" href="profile.php"><i class="fa fa-user"></i> <?= $_SESSION['user'] ?></a></li>
        <?php else :; ?>
            <li><a id="home" href="index.php"><i class="fa fa-home"></i> HOME</a></li>
            <li><a id="catalog" href="catalog.php"><i class="fa fa-list"></i> CATALOG</a></li>
            <li><a id="about" href="about.php"><i class="fa fa-pencil"></i> ABOUT</a></li>
            <li><a id="basket" href="basket.php"><i class="fa fa-beer"></i> BASKET</a></li>
            <li><a id="faq" href="faq.php"><i class="fa fa-question"></i> FAQ</a></li>
            <li><a id="logout" href="logout.php"><i class="fa fa-sign-out"></i> LOGOUT</a></li>
            <li><a href="#"><i class="fa fa-search"></i> <input
                            style="box-sizing: border-box; border: 2px solid; border-radius: 15px; height: 40px;width: 300px;"
                            type="text" placeholder=" Search..." name="search"></a></li>
            <li><a id="profile" href="profile.php"><i class="fa fa-user"></i> <?= $_SESSION['user'] ?></a></li>
        <?php endif; ?>
    </ul>
</nav>

Upvotes: 2

Related Questions