How to check if a session exists

Asked

Viewed 50 times

-1

How do I check if a session exists and if it exists, redirect to a specific page? I tried it this way, but it’s not working.

    <?php

      if(isset($_SESSION)){

       header('Location: painel.php');
       exit();

      }
    ?>

In case my idea is not to let the user return to the login page if he has already logged in to the site.

  • 2

    Dear Jhonatan put the session_start() at the beginning of the script. I recommend that you study based on the documentation: https://www.php.net/manual/en/ref.session.php, because you will learn the basics more "correctly"

1 answer

1


If you want to validate if the session does not exist, and prevent page loading by the user, you need to do the reverse logic:

If the session does not exist.

<?php
// Verifica se a sessão da aba do navegador existe
// Se não existe, inicia.
// Iniciei a função dentro do IF para evitar exibição de erros de cabeçalho

if(!session_id()){session_start();}

// Se não existe, redireciona...
// Verifica se não está definida a sua sessão,
// ou uma sessão específica.

// Exemplo 1:
if(!isset($_SESSION['logado'])
{
    header('Location: pagina_encaminhada.php');
    exit();
}

// Exemplo 2:
if(!isset($_SESSION))
{
    header('Location: pagina_encaminhada.php');
    exit();
}
?>

Browser other questions tagged

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