Ben Parry Ben Parry - 4 years ago 70
HTML Question

PHP - Problems displaying information once user has signed in

I had this working a few days ago, but I cannot seem to get the session ID to display on screen once the user has signed into their account. I have two PHP which I've been working on and I've checked both for errors using checkers online and come up short with nothing. So with what's below, once the user has signed in, it will display their session ID inside the site's header, but even though I am correctly signing in (I've checked it's logging in with my database), all it does it display "You are not logged in!".

Login.inc.php

<?php
include '../dbh.php';

$email = $_POST['email'];
$pwd = $_POST['pwd'];

$sql = "SELECT * FROM user WHERE email='$email' AND pwd='$pwd'";
$result = mysqli_query($conn, $sql);

if (!$row = mysqli_fetch_assoc($result)) {
echo "You are not signed in!";
} else {
$_SESSION['id'] = $row['id'];
}
header("Location: ../index.php");
?>


site_header.php

<head>
<?php
session_start();
?>
<link rel="stylesheet" type="text/css" href="vendors/css/normalize.css">
<link rel="stylesheet" type="text/css" href="vendors/css/grid.css">
<link rel="stylesheet" type="text/css" href="vendors/css/ionicons.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link href="https://fonts.googleapis.com/css?family=Lato:400,300,100,300,200italic" rel="stylesheet" type="text/css">
<title>iBPBuyer</title>
</head>
<body>
<header>
<nav>
<ul>
<li><a href="index.php">HOME</a></li>
<li><a href="signup.php">SIGN UP</a></li>
<?php
echo "<form action='includes/login.inc.php' method='POST'>
<input type='email' name='email' placeholder='E-Mail'>
<input type='password' name='pwd' placeholder='Password'>
<button type='submit'>Login</button>
</form>";
?>
<?php
if(isset($_SESSION['id'])) {
echo $_SESSION['id'];
} else {
echo "You are not logged in!";
}
?>
</ul>
</nav>
</header>

Answer Source

You don't just want to be echoing stuff out. I would recommend using an authenticated flag

<?php
include '../dbh.php';

session_start(); //THIS APPEARS TO BE MISSING 

$email = $_POST['email'];
$pwd   = $_POST['pwd'];

$sql    = "SELECT * FROM user WHERE email='$email' AND pwd='$pwd'";
$result = mysqli_query($conn, $sql);

if (!$row = mysqli_fetch_assoc($result)) {
    //You have Session no matter what for this user
    $_SESSION['authenticated'] = false;
} else {
    $_SESSION['authenticated'] = true;
    $_SESSION['id'] = $row['id'];
}
header("Location: ../index.php");
?>

Then in your view you can do this

<?php
if($_SESSION['authenticated']) {
    echo $_SESSION['id'];
} else {
    echo "You are not logged in!";
}
?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download