Display login username on screen

Asked

Viewed 1,791 times

0

Hello! In the restricted page of my site, you need to present the name of the logged-in user, the same occurs in the form that is displayed. But I noticed you’re not showing up, not on the "Hello" or the form. I analyzed the code and couldn’t find anything different than what I had left before. I would like a little help to identify the possible mistake of why not present. :)

This is how it is on the restricted page to search and display the user name on screen:

Olá, <p id="usuario"></p>
<script>document.getElementById("usuario").innerHTML = localStorage.getItem("usuario");</script>

And so it is in the login check code, where I search for the i'ds presented in the database:

 <?php
    session_start();
    include_once 'config.php';
    ini_set('display_errors',true);
    ini_set('display_startup_erros',1);
    error_reporting(E_ALL);
    if ( isset( $_POST ) && ! empty( $_POST ) ) {
        $dados_usuario = $_POST;
    } else {
        $dados_usuario = $_SESSION;
    }
    $validacao = login($dados_usuario['usuario'], $dados_usuario['password']);
    if(isset($dados_usuario)){
        if ($validacao) {
            $_SESSION['logado'] = true;
            $_SESSION['nome_usuario'] = $validacao->user_name;
            $_SESSION['usuario'] = $validacao->user;
            $_SESSION['user_id'] = $validacao->user_id;
            $_SESSION['nom_clin']= $validacao->nom_clin;
            ?><script>localStorage.setItem("usuario", "<?php echo $validacao->usuario?>");</script><?php
  }
       exit;
        }
     else {
         echo 'Login e Senha incorretos. Favor voltar a página e tentar novamente.';
        // Continua deslogado
        $_SESSION['logado'] = false;
        // Preenche o erro para o usuário
        $_SESSION['login_erro'] = 'Usuário ou senha inválidos';
        //session_destroy();
        //header("Location: restrito.php");
        //exit;

    }

        function login($login, $senha)
        {

            try {
                $sql = "SELECT cod_clin, user, user_name, user_id, nom_clin FROM usuarios WHERE user_id='$login' AND user_password='$senha' LIMIT 1";
                $conn = getConexao();
                $result = $conn->query($sql);
                $row = $result->fetch(PDO::FETCH_OBJ);
                return $row;

            } catch (PDOException $e) {
                echo $e;
                return false;
            }
        }
?>

And the ID’s match the database.

  • What are the properties returned by the function login($dados_usuario['usuario'], $dados_usuario['password'])? For in a moment you wear $_SESSION['usuario'] = $validacao->user; and in another you use <?php echo $validacao->usuario?>. It may be that the property $validacao->usuario does not exist and yes $validacao->user.

  • You tested by putting the ; as I mentioned in my reply ? Where are the variables declared $login e $senha present in your darling ?

  • @Magichat I tested yes, and did not influence anything. About 2 months ago, the presentation of the user’s name appeared normally without any problem. And last week I went through the site archives and that’s where I saw it no longer presents.

  • Okay and the variables ?

  • @Magichat Online " Function login($login, $password) {"

  • I know it sounds like a detail but the lack of ";" can cause a big headache in the codes I myself have had a hard time with it and looking at the code missing a ";" after: "<? php echo $validacao->usuario". Already gave a var_dump($_SESSION['name_da_sessao']) to see if everything is all right?

Show 1 more comment

4 answers

2

PHP SESSION

You have stored the user name in SESSION so just call it in the code, change it as follows:

Olá, <p id="usuario"><?php echo $_SESSION['nome_usuario']; ?></p>
// Pode remover o Script

To access data from SESSION it is important to start the session, using session_start(), as follows:

<?php session_start(); // é possível inicializar o SESSION logo no início do arquivo.
  • @Inezboldrin good morning, is as Thiago mentioned, as it is a global variable you can use it in any part of the project just by calling the variable.

  • Thiago, I did it the way you put it and didn’t present anything. session_start had already been placed before, which was also not displaying any screen name.

  • Shortly after the session_start() makes a print_r($_SESSION); and check if you have something saved in the session, if it is empty check if you logged in on the cloud where you do the validation.

  • In the file that checks the user login is already with session_start. I put the print and opened the console, it is empty.

  • the session_start(); is the first thing on the page? Puts as the first thing. One more test, makes a echo $validacao->user_name; just before you put this variable into the session and check that it is not blank!

  • Thiago, after I put the print and updated the page (now a little bit, again), presented at the beginning of the page the following "Array()". What could be?

  • $_SESSION is an Array() and is empty, but this is progress, is using print_r? It has to be print_r!

Show 3 more comments

1

Don’t forget to log in :

$validacao = login($dados_usuario['usuario'], $dados_usuario['password']);
if(isset($dados_usuario))
{    if($validacao)
     {    session_start();
          //continue

And then you can call it like in Thiago’s answer...

Olá, <p id="usuario"><?php echo $_SESSION['nome_usuario']; ?></p>

Another detail is that the way it is in your question

<?php echo $validacao->usuario?>

We’re missing a ;, then if you are going to do with js start by changing to :

<?php echo $validacao->usuario;?>
------------------------------^
  • This validation I already have in the verified file_login.php. When I put in the restricted.php file presented the blank page.

  • Edit your question and place the previous code block relevant to the session part....

  • The line that has "Hello" is where I want the user name to appear on screen. On the line that has $validation is where the verification code is (to verify user and password), where the same id’s match those in the database.

  • Well, what happens is this, you have a previous code that can influence the behavior of what is being proposed in the question, so it’s easier to solve if you post these tmb codes...

0

You could create an HTTP request method for the code to return a JSON containing all the data you want to use, and pass to Javascript using Jquery.

$.getJSON("DadosDoUsuario.php").
done(function (dados) {
$("#nomedadiv").html("Olá "+dados.NOMEUSUARIO);
});

0

Hello,

Following the query $sql = "SELECT cod_clin, user, user_name, user_id, nom_clin FROM usuarios WHERE user_id='$login' AND user_password='$senha' LIMIT 1"; the PDO will return you the following properties: cod_clin, user, user_name, user_id, nom_clin.

object(stdClass) {
    public $cod_clin;
    public $user;
    public $user_name;
    public $user_id;
    public $nom_clin;
}

That is, when calling $validacao->usuario will return that property usuario was not defined, breaking the application. Try calling $validacao->user

  • I switched the $validacao->usuario for $validacao->user and also did not present on screen the user.

  • Of these columns cod_clin, user, user_name, user_id, nom_clin, which returns the user name?

  • Is the user even if it returns.

  • Makes a var_dump($validacao); after $validacao = login($dados_usuario['usuario'], $dados_usuario['password']); and see if it is returning the user data. If you can share the return.

Browser other questions tagged

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