Session check problem in PHP

Asked

Viewed 138 times

0

I made a small login screen using PHP session, but when I do the test to check if the session is already created the condition never "falls" in else.

Code:

<?php
    if(!isset($_SESSION))
    {
        session_start();
    }else{
        echo "<p>Sessao já existia</p>";
    }
    $_SESSION['usuario'] = $_POST['nome'];
    $_SESSION['name'] = "Minha Sessao";
?>

Usuário Logado:<p id='teste'></p>
<script type="text/javascript">
    var usuario = document.cookie;
    alert(usuario);
    document.getElementById('teste').innerHTML = usuario;
</script>
<a href="logout.php">Logout</a>

  • 2

    This is because the superglobal variable $_SESSION is never set until you call the function session_start, function to initialize session variables.

  • But if I gave a session_start() before the check it wouldn’t just fall into Else ?

  • 1

    Luiz, do not make edits to the question that Sconfigure and invalidates the answers given. If the answers don’t meet your need means you didn’t ask what you wanted, then ideally create another question explaining the problem. The issues in the question are allowed when they aim to improve it, not change it.

2 answers

0


Use session_status(), to check the session status.

Use

if(session_status() === PHP_SESSION_NONE) session_start();

Never use

if(!isset($_SESSION)) session_start();

or

if(session_id() === "") session_start();

Both checks will fail after a call to session_write_close ().


Do not use

if(session_status() !== PHP_SESSION_ACTIVE) session_start();

If sessions are disabled on php.ini the code will fail.

  • Hello, I did the check as you suggested but I did not get the result I expected. Maybe my question wasn’t clear, but what I want to do is prevent multiple sessions from being created and when a new user logs in and just changes the values of the $_SESSION

  • @Luizfelipedasilva You happen to think that the session will be shared among all users of the site?

  • @Luizfelipedasilva each user has their session. As Woss said, The session is not shared.

  • Got it, thanks for your help.

-2

My suggestion is that you check in the following way.

<?php

session_start();

if(!isset($_SESSION['usuario'])){
    echo "<p>Usuário não está logado</p>";
    $_SESSION['usuario'] = $_POST['nome'];
    $_SESSION['name'] = "Minha Sessao";

}else{
    echo "<p>Usuário logado no sistema</p>";
}
  • And how would that be different from the question?

  • Simple ... this way he will always have the login and can control the access checking the user value in the session.

Browser other questions tagged

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