Securing PHP Files using HTTP Authentication

4.33 (72)

Allowing Multiple Users

There are two main methods of allowing multiple users password protected access to your website. The first being username/password files and the second being username/password tables in a database. As many people use database nowadays, I will now focus on this method. In order to implement a file based version of this script, you will have to save usernames and passwords to a file (username,password on each line). You would then read each line, and check if the username and password match.

Back to the main topic of databases! They are useful in this sense, and often websites have a dynamic Content Management System (CMS) for their website which has allows for several users or authors to access this area. The author data is already stored in the database, so there is no need to add a file or more data. I'm going to assume you know a little about how to access MySQL databases in this section, but don't worry, it should be too difficult.

To start of with, we need a table of the usernames and passwords. This is SQL which can be executed by running MySQL via the command line, or by using a script such as phpMyAdmin.

CREATE TABLE 'users' ( 
'userID' INT NOT NULL AUTO_INCREMENT,
'username' VARCHAR( 20 ) NOT NULL ,
'password' VARCHAR( 20 ) NOT NULL ,
PRIMARY KEY ( 'userID' ) ,
UNIQUE ( 'username')
);


Now, let's enter a few users:

INSERT INTO 'users' ( 'userID' , 'username' , 'password' ) 
VALUES ( '', 'john, 'secret');

INSERT INTO 'users' ( 'userID' , 'username' , 'password' ) 
VALUES ( '', 'peter', 'othersecret');

INSERT INTO 'users' ( 'userID' , 'username' , 'password' ) 
VALUES ( '', 'billy', 'ilovecats');


Now we have our database table setup called users. On my computer, I have this table in a database called myCms so we will use that in our examples.

To get going, we must first connect to the database. At the same time, we are also going to convert all this into our own function so that it is again reusable in the future.

Connect
<?php

function validateUser () {
    
mysql_connect('dbusername''dbpassword''localhost') or die(mysql_error());
    
mysql_select_db('myCms') or die(mysql_error());

}

?>


Here we have connected to the database using our database name and password. You must change the username and password for your setup. We then select our database (myCms). If any errors occur the script is terminated and the error is outputted using die(mysql_error()). This is especially useful in determining any bugs in your scripts.

Now we must query the database and check if the username and password that has been entered is correct:

<?php
function validateUser () {
    
mysql_connect('dbusername''dbpassword''localhost') or die(mysql_error());
    
mysql_select_db('myCms') or die(mysql_error());


    
$user = @addslashes($_SERVER['PHP_AUTH_USER']);
    
$password = @addslashes($_SERVER['PHP_AUTH_PW']);
    
    
$sql "SELECT Count(*) as Number FROM users WHERE username='" $user "' AND password='" $password "'";
    
$query mysql_query($sql) or die(mysql_error());

    
$result mysql_fetch_array($query);
    
$NumberOfUsers $result['Number'];

}
?>


This may be a little daunting but it is simple in essence. All we have done, is modified the input username and password by calling addslashes() on them. This is a security issue and should always be performed on user input to database, to prevent them from gaining unauthorized access.

We then have our query, which selects (gets) numbers of records that meets our conditions. Our conditions state the username and password must match the ones that the user has entered.

Following this, we execute the query, get the results and then assign the result called Number to a variable called $NumberOfUsers so that we can use it. Now all that's left to do, is the standard header output:

Altogether Now
<?

function validateUser () {
    
mysql_connect('dbusername''dbpassword''localhost') or die(mysql_error());
    
mysql_select_db('myCms') or die(mysql_error());


    
$user = @addslashes($_SERVER['PHP_AUTH_USER']);
    
$password = @addslashes($_SERVER['PHP_AUTH_PW']);
    
    
$sql "SELECT Count(*) as Number FROM users WHERE username='" $user "' AND password='" $password "'";
    
$query mysql_query($sql) or die(mysql_error());

    
$result mysql_fetch_array($query);
    
$NumberOfUsers $result['Number'];

    if (
$NumberOfUsers != 1) {
        
        
header('WWW-Authenticate: Basic realm="Site Administration Area"');
        
header('Status: 401 Unauthorized');
        
/* Special Header for CGI mode */
        
header('HTTP-Status: 401 Unauthorized');
    
        
?>

<html>
<head>
<title>Access Unauthorized</title>
</head>
<body>
<h1>Access to the requested page denied</h1>
You have been denied access to this page for entering an 
incorrect or non-exist username and password.<br><br>
Press 'Refresh' to retry the login procedure.
</body>
</html>
        <?php

        
exit;
    } 
}    

?>


This is essentially the same as the code of the previous page, however this time, as we have queried the database for the number of users where the username/password match, we do not have to again check the input username/password. Instead, we have the number of users with the correct match – this should equal to 1 or 0, and never more. Hence, we check if the number does not equal to 1, if so, we send the headers.

As we have defined this all in a function, we can again move this into a library file and now we can call this on every page using this method:

Multiple Pages
<?php

require_once('global.php');
validateUser();

echo 
'Welcome to the secured area!';
?>


This is almost the same as previously, except there are no parameters for the validateUser() function as all the username / password combinations are taken from the database.

I hope this article has helped you gain an understanding on how to password protect your website using this simple but efficient method. You should now try it out for yourself, or maybe consider implementing the file based version.
Rate this article: BAD 1 2 3 4 5   GOOD
<<     Page 3 of 3

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!

Ads

PHPNerds Newsletter