Variable $ _SESSION of empty PHP

0

I have a login problem. I'm writing a user ID in a session variable, so it logs in, but this variable is getting empty, does anyone know why?

PHP

<?php
 session_start();
 $username = $_POST['name'];
 $password = $_POST['pwd'];

 include("conexao.php");
 mysql_select_db("mg", $conn) or print(mysql_error()); 

 $query = "SELECT id_usuario, nm_login, nm_senha, nm_nome, nm_sobrenome, nm_imagem FROM tbl_usuario WHERE nm_login='".$username."' AND nm_senha='".$password."'";

 $result = mysql_query($query,$conn) or die(mysql_error());
 $num_row = mysql_num_rows($result);
 $row=mysql_fetch_array($result);
 if( $num_row >=1 ) {
   echo 'true';
   $_SESSION['usuario']=$row['id_usuario'];
   $_SESSION['login']=$row['nm_login'];
   $_SESSION['nome']=$row['nm_nome'];
   $_SESSION['sobrenome']=$row['nm_sobrenome'];
   $_SESSION['avatar']=$row['nm_imagem'];
 }
 else{
   echo 'false';
 }
?>

In this line it appears empty, if I give F5 it loads the variable

    if(!isset($_SESSION['usuario'])){
        echo "<li><a href='#' id='login-link'>Login</a></li>";
    };

You're giving the error

  

Notice: Undefined index: user

Thanks

    
asked by anonymous 29.10.2014 / 18:51

1 answer

1

This can occur if for some reason you are recreating your session with every post / submit / refresh.

If this happens, it will lose the values of the old session.

Take a look, if the session_start () code is not running at every page interaction.

Try using a singleton in the session to avoid this problem:

if (!isset($_SESSION)){
    session_start();
}
    
29.10.2014 / 19:02