如何在 PHP 中使用数据会话?

How can I use data sessions in PHP?

我正在尝试使用数据会话来检查表单,但是,当我发送用户名和密码时,程序会检查密码,这 return 到主页。

我在密码字段上写了 1234,但我不明白为什么这不能正常工作。

<!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>

第二页

<!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>

session_start() 必须在任何输出到浏览器之前调用。

请首先更新所有使用会话的 php 页面上的代码。

<?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>