Daniel Serretti
Daniel Serretti

Reputation: 342

How to show username between html with PHP

My issue is: I have a login system and I wanna show the current username in the page.

calendar.php:

// SOME CODE

      <ul class="nav navbar-nav">
        <li><a href="#">Welcome <? echo $_SESSION['username'] ?></a></li>
        <li><a href="logout.php">Logout</a></li> <!-- class="active" -->
        <li><a href="#">Store location <span class="label label-danger">65</span></a></li>
      </ul>

// SOME CODE

This shows the "Welcome" but don't show username... How can I do this? Thank you all in advance.

Upvotes: 2

Views: 104

Answers (3)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

You forgot to write php in your code:--

<ul class="nav navbar-nav">
        <li><a href="#">Welcome <?php echo $_SESSION['username'] ?></a></li>
        <li><a href="logout.php">Logout</a></li> <!-- class="active" -->
        <li><a href="#">Store location <span class="label label-danger">65</span></a></li>
      </ul>

Note:-

1.This code file name will be .php not .html and if your Session have username index and have some value then only it will show.

2.As you asked for the error you need to put this code on very upside of your php page

<?php 

session_start();
$_SESSION['username'] = 'any user name';

After that my above code and then everything works fine.

3.If you want this session value to any other page on that page write first session_start(); on top and then you will get the value.

Upvotes: 2

Pedro Lobito
Pedro Lobito

Reputation: 98961

Make sure $_SESSION['username'] is already set, i.e:

index.php

<?php
session_start();
$_SESSION['username'] = "someusername";

calendar.php

<?php
session_start();
?>
  <ul class="nav navbar-nav">
    <li><a href="#">Welcome <?php echo $_SESSION['username'] ?></a></li>
    <li><a href="logout.php">Logout</a></li> <!-- class="active" -->
    <li><a href="#">Store location <span class="label label-danger">65</span></a></li>
  </ul>

Note:

Ensure session_start(); is the first statement on the script, i.e.:

<?php
session_start();

Otherwise you may get the error:

"Headers already sent..."


Learn how to use php sessions across multiple files here

Upvotes: 3

kainaw
kainaw

Reputation: 4334

Unless you are using a rather old system, you need

<li><a href="#">Welcome <?php echo $_SESSION['username'] ?></a></li>

If it still doesn't show, ensure that the page is being parsed for PHP. Then, make sure that $_SESSION['username'] has a value.

Upvotes: 2

Related Questions