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

时间:2019-03-04 13:15:48

标签: php session php-7.0

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

我在密码字段上写了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>

1 个答案:

答案 0 :(得分:0)

在向浏览器输出任何内容之前,必须先调用

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>