Search code examples
phpsessionheaderconnectionisset

How to check whether the user is logged in?


I try in my page "connexion.php" to verify whether the user is already logged or not. Normally, my code should work, but it doesn't. The error seems to appear in the redirection. Here is my code.

x

If i do a var_dump(), my $_SESSION['id'] does exist and if i had a echo''; after the header("Location: ../../Index/v/index.php");, the text is well displayed so the error seems to be in the redirection, even if it's written good.


Solution

  • A header() command will only actually work if it is sent to the client BEFORE any other tranfer of data has happened, so because you have already output the HTML from <!DOCTYPE html> to <body> the header() will be ignored.

    Try doing that checking before you output any HTML

    <?php
        //Ouverture session
        session_start();
    
        if(isset($_SESSION['id'])) {
            header("Location: ../../Index/v/index.php");
        }
    ?>
    <!DOCTYPE html>
    <html>
    
    <head>
        <title>Undbe</title>
        <meta charset="utf-8" />
    </head>
    
    <body>
    <?php
    
        if(isset($_COOKIE['login_email']) && isset($_COOKIE['login_pass']))
        {
            // Soon
        }
    
        else
        {
    ?>
            <h1>Connexion</h1>
    
            <form method="post" action="../c/c_connexion.php">
                <label for="email">Votre email :</label> <input type="email" name="email" id="email" /><br />
                <label for="password">Votre password :</label> <input type="password" name="password" id="password" /></br><br />
                <input type="checkbox" name="remember" id="remember" /> <label>Rester connecté.</label>
                <input type="submit" value="Envoyer" />
            </form>
    <?php
        }
    
    ?>
    </body>
    
    </html>