为什么我的 <a href> link 不起作用?我的测试 link 可以打开 Testing.php 文件,但其他文件似乎只是刷新 Index.php

Why doesn't my <a href> links work? My testing link works opening up a Testing.php file but the others just seem to refresh the Index.php

  1. 这是我的 Index.php 文件,不会让我进入任何其他页面

    <?php
        session_start();
        include_once 'dbconnect.php';
        //Connecting to the database
    
            if(!isset($_SESSION['user'])){
                header("Location: Login.php");
                }
            //If the user is not logged in, this code will redirect them to the Login page
    
            $res=mysql_query("SELECT * FROM users WHERE UserID=".$_SESSION['user']);
            $userRow=mysql_fetch_array($res);
            /*This is finding all the data based on the User's User ID.
             This is very safe as it will only find the data relevant to the User that is logged in */
    ?>        
    

    欢迎 -

    <h1>Welcome <?php echo $userRow['Username']; ?> to our website</h1>
    <!-- This here is doing the same thing as before -->
    <a href="Logout.php?logout"> Log Out</a> | <a href="MySubjects.php"> My Subjects</a> |
    <a href = "NewSubject.php"> Add a new subject</a>
    
    <a href = "Test.php"> Testing</a>
    

2.This 是我的 NewSubject.php 文件。这和MySubjects.php都相似

    <?php
    require_once('Dbconnect.php');
    //Connecting to the database

    if(!isset($_SESSION['user'])){
            header("Location: Login.php");
        }

    //User is being redirected to the login page if they are not logged in.

    else{
    $res=mysql_query("SELECT * FROM subjects WHERE UserID=".$_SESSION['user']);
    $userRow=mysql_fetch_array($res);
    }
    //This is fetching the data based on the Session Variable UserID
    ?>

</head>
<title> Add a new subject</title>

<body>

    <form method = "Post">

        <select name = SubjectName>
            <option value="Maths">Maths</option>
            <option value="FurtherMaths">Further Maths</option>
            <option value="EnglishLanguage">English Language</option>
            <option value="EnglishLiterature">Engliash Literature</option>
        </select>

    </form>

    <a href="Logout.php?logout"> Log Out</a> | <a href="My Subjects.php"> My Subjects</a> |
    <a href = "NewSubject.php"> Add a new subject</a>

</body>

  1. 抱歉,如果这很明显或其他什么,但我是 PHP 的新手,并且正在与朋友一起作为个人项目进行此操作。我认为 PHP 代码有问题,因为我的 test.php 文件 link 工作正常,只有 html 和 body 标签中有此代码:

这是一个测验!

这可能导致您重定向:

if(!isset($_SESSION['user'])){
     header("Location: Login.php");
}

在这种情况下,Login.php 导致重定向到 Index.php,尽管已登录。

您需要设置某种会话控制器(可以是简单的 Sessions.php),在其中执行会话检查以确保当前用户已登录,然后在那里设置 $_SESSION['user'] 或重定向到 Login.php。

然后您需要在依赖它的所有文件中要求该文件。


那里有关于 Cookie/Session 控制的教程,我个人会四处搜索。

我做了很多研究,找到了我的代码中出错的答案。问题是在我每个页面的开头我忘记写以下内容:session_start();

这意味着,每次我尝试打开 link,它都不遵循 if(!isset($_SESSION['user'])) 因为它不存在于该页面中(因为没有设置会话变量)。

因此,当我写 session_start(); 时,它完美地工作了!