DaNg Sayz
DaNg Sayz

Reputation: 9

PDO: isset & session not displaying properly

I'm having a hard time displaying a user's information after the user has logged in.

This is my index.php file:

<?php
require 'core/db/connect.php';

    if(isset($_SESSION['username'])){
        include 'includes/menu.php';
    }
    else{
        echo '<a href="register.php">Register</a><br />';
        echo '<a href="login.php">Login</a><br />';
    }
?>

For profile.php, whenever I echo something out, it doesn't echo:

<?php 
if(isset($_SESSION['username'])){
    include 'core/db/connect.php';

    $username = $_SESSION['username'];

    $query = dbConnect()->prepare("SELECT username FROM users WHERE username = :username");
    $query->execute(array(':username' => $username));
    $row = $query->fetch();

    echo 'Logged in as: ', $row['username'];
}

?>

This is my first script, so sorry!

And if this helps, here is my login.php:

<form method="POST">
<input type="text" name="username" placeholder="username"><br/>
<input type="password" name="password" placeholder="password"><br />
<input type="submit">
</form>

<?php
    if(isset($_POST['username'], $_POST['password'])){
    require 'core/db/connect.php';

    $query = dbConnect()->prepare("SELECT username, password FROM users WHERE username = :username AND password = :password");
    $query->execute(array(
        ':username' => $_POST['username'], 
        ':password' => $_POST['password']
    ));

    if($query){
        header('Location: index.php');
    }
    else{
        echo 'Username or Password is wrong.';
    }
}
?>

Upvotes: 0

Views: 541

Answers (2)

Andy Librian
Andy Librian

Reputation: 913

In your code, you start session_start() in connect.php. That means, you read $_SESSION['username'] before the session starts.

To fix this, You need to call session_start() before reading $_SESSION variable. Try to change your code from:

<?php 
if(isset($_SESSION['username'])){
    include 'core/db/connect.php';

to:

<?php

session_start();
if(isset($_SESSION['username'])){
    include 'core/db/connect.php';

Upvotes: 0

Mayur Kukadiya
Mayur Kukadiya

Reputation: 994

Before you use sessions in PHP you have to call session_start();.

Upvotes: 1

Related Questions