简体   繁体   中英

Secure pages with PHP/.htaccess?

www.example.com/index.html on my website is a page that asks for a password, and when entered, runs through 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');
}
?>

And then gets redirected to www.example.com/kareha/ .

The problem is, anyone can just type in and directly navigate to www.example.com/kareha/ .

Is there any way I can protect this index file (or anywhere else on the site) so anyone who isn't logged in is redirected to the main login page?

Also, would it help if it was protected through .htaccess ? ( /kareha/index.html is automatically updated according to a template, which has broken every time I mess around with it)

Edit: Maybe something along the lines of starting a session with /login.php and then having .htaccess in the /kareha/ folder check for the session?

you need to use sessions or .htpasswd. To use sessions, change your html files to 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
    session_start();
    if(!isset($_SESSION['loggedin'])) {
        // redirect to login page
        header('Location: http://example.com/index.html');
    }

// put rest of page here

you can read about sessions here: http://www.php.net/manual/en/book.session.php

Edit: I misread the original question. Revised...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM