add password protection

Associate
Joined
26 Jan 2006
Posts
1,502
Hey,

I need a way to protect a specific .html file from being read by my viewers without login first. I already have a form ready with all necessary fields and using "post" username and password will end up in $_POST['username'] and $_POST['password'].

My question is, how I am supposed to sent the user to the specific html if the login is successful (I know how to code a check in PHP) without any possible way to get to it without going through login?

Thanx!
 
I had never done this before either, so I had a play arround and came up with this (Apache-specific) :

.htaccess file in the folder you want to protect, containing :

Code:
RewriteEngine on
RewriteRule (.*)\.html /login.php?file=$1

Basically changes every request to a file ending in .html to login.php with the name of the file as a CGI parameter, eg : index.html -> login.php?file=index.html

Now make a login.php which tests a cookie or session variable indicating if the client is authenticated. If it is authenticated, simply readfile() the html file contents, if it isn't authenticated, display a login dialog.

Hacky PHP follows :

Code:
<?php
session_start();

$users = array(
        "someuser" => "1234"
);

$file = substr($_SERVER["REQUEST_URI"], 1);

if (isset($_REQUEST["username"]) && isset($_REQUEST["password"])) {
        while (list($username, $password) = each($users)) {
                if ($username == $_REQUEST["username"] && $password = $_REQUEST["password"]) {
                        $_SESSION["authenticated"] = 1;
                        break;
                }
        }
        if ($_SESSION["authenticated"] == 0) {
                echo "<p>invalid user or password</p>";
        }
}

if (!isset($_SESSION["authenticated"]) && $_SESSION["authenticated"] == 0) {
        echo <<<EOF
        <form method="post">
        Username: <input type="text" name="username" /><br />
        Password: <input type="password" name="password" /><br />
        <input type="submit" value="Login" />
        </form>
EOF;
} else {
        readfile($file);
}
?>

Works on my server :)
 
Last edited:
Back
Top Bottom