为什么不';t我的<;a href>;链接有效吗?我的测试链接可以打开testing.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.这是我的NewSubject.php文件。this和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文件链接运行良好,它只在html和body标记中包含以下代码:

这是一次考验!

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

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

因此,当我编写session_start();时;,它工作得很好!

这可能导致您重定向:

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

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

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

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


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