PHP -不能在"if"中更改会话变量声明


PHP - Cannot change session variable in an "if" statement

在未登录的情况下尝试重定向页面。我来解释一下我的意思。

在index.php:

<?php
// initialization of login system and generation code
$oSimpleLoginSystem = new SimpleLoginSystem();
echo $oSimpleLoginSystem->getLoginBox();
session_start();
$_SESSION["loggedin"] = False;
// class SimpleLoginSystem
class SimpleLoginSystem {
    // variables
    var $aExistedMembers; // Existed members array
    // constructor
    function SimpleLoginSystem() {
        $this->aExistedMembers = array(
            'test' => MD5('test'),  //Sample: MD5('qwerty')
        );
    }
    function getLoginBox() {
        ob_start();
        require_once('login_form.html');
        $sLoginForm = ob_get_clean();
        $sLogoutForm = '<a href="'.$_SERVER['PHP_SELF'].'?logout=1">logout</a>';
        if ((int)$_REQUEST['logout'] == 1) {
            if (isset($_COOKIE['member_name']) && isset($_COOKIE['member_pass']))
                $this->simple_logout();
        }
        if ($_REQUEST['username'] && $_REQUEST['password']) {
            if ($this->check_login($_REQUEST['username'], MD5($_REQUEST['password']))) 
            {
                $_SESSION["loggedin"] = True;
                $this->simple_login($_REQUEST['username'], $_REQUEST['password']);
                header( 'Location: /site.html' );
            } 
            else {
                return 'Username or Password is incorrect' . $sLoginForm;
            }
        } else {
            if ($_COOKIE['member_name'] && $_COOKIE['member_pass']) {
                if ($this->check_login($_COOKIE['member_name'], $_COOKIE['member_pass'])) {
                    header( 'Location: /site.html' );
                }
            }
            return $sLoginForm;
        }
    }

在site.php:

<?php
session_start();
if ($_SESSION["loggedin"] == 0)
{
    header( 'Location: http://test-weeabear.c9users.io/' );
}
else
{
return "It worked!"
}
?>

为什么当我打开site.html,它重定向我回到index.html,甚至在登录后?

注意:我改变了一些东西,比如链接和文件名。对隐私。

在您的site.php开始时需要session_start()

将文件扩展名从。html更改为。php

您正在调用getLoginBox,然后将loggedin更改回false。你需要在标题重定向后包含一个出口。

:

header( 'Location: /site.php' );//changed to file extension as .php
exit;