phpsessionphp-7.0

How can I use data sessions in PHP?


I'm trying to use data sessions for checking a form, but, when I send user and password, and programme goes to check password, this return to main page.

I write 1234 on password field, but I can't understand why this don't work correctly.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Check</title>
</head>
<body>
    <?php
        $usuario = trim(htmlspecialchars($_REQUEST['username'], ENT_QUOTES, "UTF-8"));
        $clave = trim(htmlspecialchars($_REQUEST['password'], ENT_QUOTES, "UTF-8"));
        setcookie("usuario", $usuario, time()+60*60*24*365);
        session_start();
        $_SESSION['nom_user'] = $usuario;
        $_SESSION['pass_user'] = $clave;
        header('Location: nacimiento.php');
    ?>
    <a href="index.php">Volver</a>
</body>
</html>

Second Page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Fecha de Nacimiento</title>
</head>
<body>
    <?php
        session_start();
        if (($_SESSION['pass_user'])=='1234'){
                echo '<form action="check.php" method="POST">';
                echo '<label for="fecha_nac">Fecha de Nacimiento</label><input type="date" name="fnacim" id="fnacim" />';
                echo '<input type="submit" name="Enviar" />';
                echo '</form>';
        } else {`enter code here`
            header('Location: index.php');
        }
    ?>
    <a href="index.php">Volver></a>
</body>

Solution

  • session_start() must be called before any output to the browser.

    Please update your code on all php pages that use the session to be included first.

    <?php
    session_start();
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Fecha de Nacimiento</title>
    </head>
    <body>
        <?php
    
            if (($_SESSION['pass_user'])=='1234'){
                    echo '<form action="check.php" method="POST">';
                    echo '<label for="fecha_nac">Fecha de Nacimiento</label><input type="date" name="fnacim" id="fnacim" />';
                    echo '<input type="submit" name="Enviar" />';
                    echo '</form>';
            } else {`enter code here`
                header('Location: index.php');
            }
        ?>
        <a href="index.php">Volver></a>
    </body>