Change navbar after user login php

Benjamin Brooks picture Benjamin Brooks · Jan 28, 2016 · Viewed 10.7k times · Source

I want the "Login/Sign up" button in the navigation bar to change to "My Account" after the user logs in.

The navigation.php file I use for this currently looks like this:

<?php 
    session_start();
    include("check.php");   
?>


<?php 

if ($_SESSION['username']){ ?>
    <div id="nav">
        <ul >
            <li class="navbar-left"><a href="artikelen.html">Men</a></li>
            <li class="navbar-left"><a href="artikelen.html">Women</a></li>
            <li class="navbar-left"><a href="artikelen.html">Kids</a></li>
            <li class="navbar-right"><a href="view_cart.php">Cart (0)</a></li>
            <li class="navbar-right"><a href="inlog.php">My Account</a></li>
        </ul>
    </div>

<?php } else { ?>
    <div id="nav">
        <ul >
            <li class="navbar-left"><a href="artikelen.html">Men</a></li>
            <li class="navbar-left"><a href="artikelen.html">Women</a></li>
            <li class="navbar-left"><a href="artikelen.html">Kids</a></li>
            <li class="navbar-right"><a href="view_cart.php">Cart (0)</a></li>
            <li class="navbar-right"><a href="inlog.php">Login / Sign Up</a></li>
        </ul>
    </div> 
<?php }
?>

The check.php file looks like this:

<?php
include('connection.php');
session_start();
$user_check=$_SESSION['username'];

$ses_sql = mysqli_query($db,"SELECT username FROM users WHERE username='$user_check' ");

$row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);

$login_user=$row['username'];

if(!isset($user_check))
{
header("Location: index.php");
}
?>

If I go to a webpage with this navigation bar I get the following error:

This webpage has a redirect loop ERR_TOO_MANY_REDIRECTS

Can someone please help me?

Answer

Rahul Kate picture Rahul Kate · Jan 28, 2016

Update your check.php to something like this.

$user_check = (isset($_SESSION['username']) && trim($_SESSION['username'])!='')?trim($_SESSION['username']):false;
if(!$user_check) header("Location: index.php");
else{
    $ses_sql = mysqli_query($db,"SELECT username FROM users WHERE username='$user_check' ");
    $row=mysqli_fetch_array($ses_sql,MYSQLI_ASSOC); 
    $$_SESSION['username']=$row['username'];
}