【问题标题】:Secure pages with PHP/.htaccess?使用 PHP/.htaccess 保护页面?
【发布时间】:2013-09-06 01:18:53
【问题描述】:

我网站上的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 检查会话?

【问题讨论】:

  • 可能无法解决您的问题,但您需要将此header('Location : http://example.com/kareha/index.html'); 更改为此header('Location: http://example.com/kareha/index.html');,因为Location: 之间添加的空格会破坏它。
  • 没注意到,谢谢!

标签: php .htaccess login passwords


【解决方案1】:

您需要使用会话或 .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...

kareha/index.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

编辑:我误读了原始问题。修改...

【讨论】:

  • 嘿蒂姆。同样的错误header('Location:http://example.com/kareha/index.php');需要header('Location: http://example.com/kareha/index.php');Location:后面的空格很重要,否则不起作用。您的操作与 OP 的相反。 ;-)
  • 谢谢。复制/粘贴/忽略 :)
  • 谢谢,这确实工作得很好。不幸的是,Kareha 程序会自动创建并运行 /kareha/index.html 在没有预先存在的情况下,因此将其更改为 index.php(尽管它在技术上确实有效)不适用于这种情况。您提到了一些关于 .htpasswd 的内容,我会检查一下。
  • 我更新了答案,因为我误读了你的问题。见更新。这有帮助吗?此外,您的服务器可能能够在 .html 文件中运行 PHP。检查一下 - 它可能会解决这个问题
  • 另外,如果您使用 .htpasswd,您将不再需要使用登录表单,因为 .htpasswd 会自动在浏览器中显示一个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 2012-06-11
  • 2018-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多