创建登录和未登录都可以查看的页面

Create page that both logged and non logged in can view

希望我能很好地解释我的问题。我尝试搜索类似的问题,但没有找到任何内容,我可能也在搜索错误的术语。

我正在开发一个新网站,用户可以在该网站上登录并修改他们的个人资料、提交食谱等。

当我第一次开始使用该站点时,我将其设置为用户必须先登录才能开始。如果他们未登录并转到个人资料页面,他们将被定向到主页。

但现在我更多地考虑这个网站,大部分内容都是隐藏的,因为您需要登录才能查看它。这不允许人们共享他们的页面,这对 SEO 也不是很好。

如何创建可以查看基本内容的页面。但是如果登录,就会有额外的功能(更新他们的个人资料、提交食谱等)。

这是我的配置文件,它会检查他们是否登录,如果没有则重定向到主页。我尝试只删除页眉,但未登录时我只看到空白页。

    //Function to check if user is logged in, and if so, return user data as an object
function check_user($secret_key, &$db) {
    if (!isset($_SESSION['userid']) || !isset($_SESSION['hash'])) {
        header("Location: index.php");
        exit;
    } else {
        $check = sha1($_SESSION['userid'] . $_SERVER['REMOTE_ADDR'] . $secret_key);
        if ($check != $_SESSION['hash']) {
            session_unset();
            session_destroy();
           header("Location: index.php");
            exit;
        } else {
            $query = $db->execute("select `id`,`nickname`, `joindate`, `last_active` from `Profile`  where `id`=?", array($_SESSION['userid']));
            $userarray = $query->fetchrow();
            if ($query->recordcount() == 0) {
                session_unset();
                session_destroy();
               header("Location: index.php");
                exit;
            }
            foreach ($userarray as $key => $value) {
                $user->$key = $value;
            }
            $query = $db->execute("update `Profile` set `last_active`=? where `id`=?", array(time(), $user->id));
            return $user;
        }
    }
}

然后在当前受保护的页面上。我会添加这个。

$userprofile = check_user($secret_key, $db);

我仍然希望能够使用 $userprofile 对象来验证用户。但我仍然希望 'unsecured' 内容可见,而不是将它们重定向到主页。

有没有办法修改我拥有的东西,希望其中一些是可以保存的。我正在使用 ADODB。

您将需要以不再重定向自身的方式重写该函数。这可以通过重写它来完成,因此它 return 用户对象或 NULL。如果它 returns NULL 调用者可以决定是否可以进行重定向。

如果您不想一次重写所有代码,您可以向您的函数添加一个新参数,该参数指示是否在您的登录检查函数中进行重定向。该参数应该有一个默认值,让函数像往常一样运行。

function check_user($secret_key, &$db, $redicrect = TRUE) {
    if (!isset($_SESSION['userid']) || !isset($_SESSION['hash'])) {
        if ($redirect) {
            header("Location: index.php");
            exit;
        }
        return NULL;
    }
    $check = sha1($_SESSION['userid'] . $_SERVER['REMOTE_ADDR'] . $secret_key);
    if ($check != $_SESSION['hash']) {
        if ($redirect) {
            session_unset();
            session_destroy();
            header("Location: index.php");
            exit;
        }
        return NULL;
    }
    //...
}