如何测试用户是否已登录


How to test if the user is logged in

我对PHP相当熟悉,想创建一个登录/注册系统,但我的代码遇到了问题。我试图测试用户是否已经登录,这样我就可以根据需要重定向他们,但每当我强制登录并转到注册页面时,它都不会根据需要将我重定向回。有人能帮我吗?这是我的密码。

注册.php

<?php
        if (isset($_SESSION['user_id'])) {
            header('index.php');
        }
     ?>
     <!DOCTYPE html>
     <html lang="en">
     <head>
        <meta charset="UTF-8">
        <title>Register Account</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
        <link rel="stylesheet" href="../css/app.css">
     </head>
     <body>
     <div class="container">
        <center><form action="#" method="POST">
            <div class="form-group top">
                <input type="text" name="firstname" class="form-control width" placeholder="Enter Firstname">
            </div>
            <div class="form-group">
                <input type="text" name="lastname" class="form-control width" placeholder="Enter Lastname">
            </div>
            <div class="form-group">
                <input type="email" name="email" class="form-control width" placeholder="Enter Email">
            </div>
            <div class="form-group">
                <input type="password" name="password" class="form-control width" placeholder="Enter Password">
            </div>
            <div class="form-group">
                <input type="password" name="password_confirmation" class="form-control width" placeholder="Confirm Password">
            </div>
            <input type="submit" name="register-button-validate" class="btn btn-success btn-lg">
        </form></center>
     </div>
     </body>
     </html>

Index.php

<?php 
    session_start();
    $_SESSION['user_id'] = 1;
?>

首先,register.php在顶部也需要这个:

session_start();

基本上,任何写入会话或从会话读取的页面都需要它。

其次,这不是重定向:

header('index.php');

这是:

header('Location: index.php');

一个不完整的头可能只是被浏览器忽略了,因为没有键告诉浏览器该如何处理该值。