Display login user name

Asked

Viewed 1,246 times

0

Good afternoon, I’m early in php and would need a help.

I have this file (index.php) where I want to show the name of the logged in user on the screen after his login, however this giving an undefined variable error ( $_SESSION).

Note: Disregard the last div=main line

            $usuario   = $_SESSION['usuarioSession'];
            $senha     = $_SESSION['senhaSession'];

                $sql = mysql_query("SELECT * FROM syslogin WHERE usuario = '$usuario' AND senha = '$senha'");

                while($linha = mysql_fetch_array($sql)){
                    $usuario = $linha['usuario'];
                    $senha   = $linha['senha'];
                    }
     ?>
    <div class="bemvindo">Bem Vindo! <strong><?php echo $usuario;?></strong> | Hoje é: <?php echo date('d/m/Y');?></div><!--Bem Vindo-->

    <div id="principal">
                <h3>Bem Vindo(a).</h3><br /><br />
                <img src="css/img/logo1.jpg" alt="logo" />
    </div> <!-- Fim da div#principal -->

    <?php include('includes/fimerodape.php'); ?>

Please where I’m going wrong?

  • That code you put out is the whole page? Remember that to work with SESSION you need to initialize it: session_start(); at the beginning of the page.

  • Be careful that the code you are using does not protect you against attacks from mysql Injection. At least pass inputs through the function mysql_real_escape_string. And consider switching to mysqli or Prepared statements

1 answer

1

That’s why you didn’t start the session, do it with the session_start():

session_start();
$usuario   = $_SESSION['usuarioSession'];
$senha     = $_SESSION['senhaSession'];

I also recommend that you make a if to check if the user has Session.

if(isset($usuario)){
    echo "<div class='bemvindo'>Bem Vindo! <strong>$usuario</strong> | Hoje é: ".date('d/m/Y')."</div>";
}
else{
    echo "Você não está logado!";
}
  • Good afternoon Francisco, Thank you very much for the tip but not wanting to be boring...could give me one more tip on this same problem. Now it is giving error in index not set ( usuarioSession e senhaSession), what do I need to do? Since thanks!

  • That’s why I recommended the if. It solves this, makes sure that there is no error if the variable is not set.

  • @Gustavohenrique If the answer I gave was right, please mark it as correct!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.