使用 PHP/.htaccess 保护页面


Secure pages with PHP/.htaccess?

我网站上的www.example.com/index.html是一个要求输入密码的页面,输入时会运行www.example.com/login.php .

<?php
if (isset($_POST['pw']) && ($_POST['pw'] == "mypassword"))
{
// Location after Logged in
header('Location: http://example.com/kareha/index.html');
}
else
{
// If not Logged in
header('Location: http://example.com/index.html');
}
?>

然后被重定向到www.example.com/kareha/.

问题是,任何人都可以输入并直接导航到 www.example.com/kareha/ .

有什么方法可以保护此索引文件(或站点上的任何其他位置),以便将任何未登录的人重定向到主登录页面?

另外,如果通过.htaccess保护它会有所帮助吗?(/kareha/index.html会根据模板自动更新,每次我弄乱它时都会损坏)

编辑:也许类似于与/login.php启动会话,然后在/kareha/文件夹中.htaccess检查会话?

您需要使用会话或.htpasswd。要使用会话,请将您的 html 文件更改为 php

这是登录脚本的顶部

<?php
    session_start();
    // see if the form has been posted
    if($_SERVER['REQUEST_METHOD'] == 'POST') {
    // check for the password
    if($_POST['pw'] == "mypassword") {
        // set a session
        $_SESSION['loggedin'] = true;
        // redirect to kareha/
        header('Location: http://example.com/kareha/index.php');
    }
} else {
    header('Location: http://example.com/index.html');
}
// put HTML and login form here...

卡雷哈/指数的最顶端.php

<?php
    session_start();
    if(!isset($_SESSION['loggedin'])) {
        // redirect to login page
        header('Location: http://example.com/index.html');
    }
// put rest of page here

您可以在此处阅读有关会话的信息:http://www.php.net/manual/en/book.session.php

编辑:我误读了原来的问题。修订。。。