Saml92 Saml92 - 6 months ago 17
HTML Question

Display html elements if a PHP session exists

I am creating a login feature for my site which if the user is logged I want it to display something differently to what it would if the user is not logged in. For this I am using sessions which I am checking if it holds a user id, if it does then display the logged in view. So far it is checking the database and then redirecting me when there is a value in the database, but it isn't changing the view.

Code I am using:

<?php
session_start();
if(isset($_SESSION['id'])){
?>
<form class="navbar-form navbar-right" role="search">
<a href="account.php" class="btn btn-inverse"><?php echo $_SESSION['name'];?></a>
<a href="userlogout.php" class="btn btn-inverse">Logout</a>
</form>
<?php
}else{
?>


<form action="userlogin.php" class="navbar-form navbar-right" role="search" method="get">
<div class="form-group">
<input type="email" class="form-control" name="Email" placeholder="Email">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Sign In</button>
<a href="register.php" class="btn btn-inverse">Register</a>
</form>
<?php
}
?>


Edit:
Sorry I left out some information the form is connected to a PHP file which looks like this:

<?php

session_start();
error_reporting(E_ALL); ini_set('display_errors', 1);
$user = "Placeholder";
$pass = "********";
$con = mysqli_connect("localhost", $user,$pass,"articlegame");
$email = $_GET['Email'];
$pass = $_GET['password'];
$result = mysqli_query($con, "SELECT id,isAdmin,name FROM users WHERE email ='$email' AND password='$pass'");
$num = mysqli_num_rows($result);
$row = mysqli_fetch_row($result);
$name = '';
$id = 0;
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$name = $row['name'];
$id = ['id'];
}
if (!$result) {
die(mysqli_error($con));
echo "Bad Connection";
}else if($num == 0){
echo "Wrong user name or password entered!";
echo " <a href='index.php'>Go back<a>";
}else{

$_SESSION['loginid'] = $id;
$_SESSION['username'] = $name;
header("Location: index.php");
}

?>

Answer

You never set $_SESSION['id'] but you check against that here:

if(isset($_SESSION['id'])){... 

You set $_SESSION['loginid'], which is what you should be checking unless you want to change your variable identifier to 'id'.

You also do not set $_SESSION['name'], instead setting $_SESSION['username'].


Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!

Never store plain text passwords! Please use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. Make sure that you don't escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.