Password Protecting PHP

Status
Not open for further replies.

clm100

Ars Legatus Legionis
13,874
Subscriptor
I need to password protect a php document. I've done it, but it doesn't work particularly well. The document does DB administration (view, add, edit and delete entries). Right now it consists of 2 pages. One is a simple HTML portal that asks for a password, and POSTS it to the "main" page (admin.php). Here's the part that deals with the password in admin.php:
code:<HR>
Code:
<?php
if (!$pass) {
 echo "You didn't enter a password, please go back and try again! \n</body> \n</html>";
 die;
} else {
 $db = @mysql_connect("localhost","bnc","$pass") or die("You've entered an invalid password, or the database is down. Go back and try again! \n</body> \n</html>");
 
}

Now, that works fine and dandy. Until someone needs to do anything. If you do a task (for this example, we'll say you deleted something) it redirects you to $PHP_SELF with various options POST'd or GET'd. Then when you return to the manager's default page it requires your password again.

Any suggestions? The most obvious one to me is to passivly post the password once it's been succesfully entered once, but is this neccesarily good? Ease and elegance are key here.
 

theFinn

Ars Tribunus Militum
2,705
Subscriptor++
Or, if you're using Apache and have PHP compiled as a module use the PHP_AUTH_* method:

code:<HR>
Code:
if (!isset($PHP_AUTH_USER)) {
        // If empty, send header causing dialog box to appear
        header('WWW-Authenticate: Basic realm="My Private Stuff"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Authorization Required.';
        exit;
}<P>else if (isset($PHP_AUTH_USER)) {
        if (($PHP_AUTH_USER != $username) || ($PHP_AUTH_PW != $password)) {
        header('WWW-Authenticate: Basic realm="My Private Stuff"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Authorization Required.';
        exit;
}
else
{
   // do stuff here
}

- theFinn
 
Status
Not open for further replies.