Hudzilla.org - the homepage of Paul Hudson
Contents > Networks > HTTP Wish List | Report Bug | About Me ]

15.4.4     Dynamic authentication

This is NOT the latest copy of this book; click here for the latest version.

A far better method to authenticate users is to compare their credentials to a members database table. By storing all your data in a database, you can easily add, edit, and revoke access permissions using PHP pages and a little SQL.

Execute this query at your MySQL prompt to create the table necessary to store our authentication details:

CREATE TABLE userauth (ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, Username VARCHAR(30), Password VARCHAR(30));

Even if you skipped the chapter on databases, you should be able to make out that the above command will create a table named "userauth" which contains three data fields in each row - an ID integer, a variable length character field "Username", and a variable length character field "Password" - just enough information to authenticate users. The ID is there to identify rows uniquely; we can refer to an authenticated user as a number, rather than as a user and password.

To allow users to add themselves to the authentication list, create a new file, addauth.php, and enter the following code:

<html>
<body>
<?php
    
if (isset($_POST['username'])) {
        
mysql_connect("localhost", "phpuser", "alm65z");
        
mysql_select_db("phpdb");
        
mysql_query("INSERT INTO userauth (Username, Password) VALUES ({$_POST['username']}, {$_POST['password']});");
        print
"Welcome to the system, {$_POST['username']}!";
    } else {
?>

<form method="post" action="addauth.php">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" value=" Add User ">
</form>

<?php } ?>

</body>
</html>

Note that I am using the database "phpdb". You may need to create this - use "create database phpdb;" from the MySQL command prompt.

With a call to mysql_query() near the top of the script, the new username and password is inserted into our table and a short confirmation message is sent back to the client.



Try running the script just by itself - you can monitor changes to your userauth database table from the MySQL command line by using the MySQL command

SELECT * FROM userauth;

Now that users can be dynamically added using addauth.php, let's modify our original auth.php script to check input against what we have in our database.

// amend the following line
if (($_SERVER['PHP_AUTH_USER'] == 'paul') && ($_SERVER['PHP_AUTH_PW'] == 'hudson')) {

// to this...
mysql_connect("localhost", "phpuser", "alm65z");
mysql_select_db("phpdb");
$result = mysql_query("SELECT ID FROM userauth WHERE Username = '{$_SERVER['PHP_AUTH_USER']}' AND Password = '{$_SERVER['PHP_AUTH_PW']}';");
if (
mysql_num_rows($result)) {

Rather than comparing the username and password to prewritten values, we now check whether they are found in our userauth table. If mysql_num_rows($result) returns one or more rows, it means we have at least one member with the credentials provided, so we should allow them access.





<< 15.4.3 Authentication over HTTP   15.5 Sending mail: mail() >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
phlames100proof@yahoo.com - 07 Jan 2009

OK, first let me ask that you please send a reply to the email address as I am realy not supose to be on the net at work...

I have tried said example above using PHP 5.2.5 on a Windows Server 2003. What happens is that no matter what user name I enter the system keeps throwing up the sign on screen (3 times) then gives me the 401 error page (never loads the rest of this page). I am sure I am doing something stupid... can never find the forrest for the trees, so I need outside advice.

Is there a configuration setting I need to change on the server?

A PHP User - 07 Jan 2009

From a more secure standpoint:
Before allowing someone to be added, check if there is already someone by that username.
MD5 the passwords before entering them into the DB.


$result = mysql_query("SELECT `username` FROM `phpdb` WHERE `username` = $username");
if(mysql_num_rows($result)) {
echo "Sorry, that username is already taken!";
} else {
...[rest]...
}


md5($password);

A PHP User - 07 Jan 2009

<?php session_start();

if ($_SESSION['loggedIn'] != TRUE )
{
header("Location: index.php");
}

# make the above the first line of your code - make sure that there are not any spaces before the <?php bit

# the header locaction should be set to your login page, therefore any unauth person on the page gets booted, okay.

chrisdavies@hotmail.com - 07 Jan 2009

I get this bit about testing a username and password against the database, what I can't get to grips with is how to boot someone off if they're not in the database. For example, what's stopping a user jumping straight to a url and bypassing the login screen?
I've tried using sessions (I'm using PHP 4.2) and I keep getting error messages stating that that:
the file or document can't be found in c:\php\includes
or undefined function $_SESSION[username']

what am I missing out, is php trying to check for a userame against some kind of file other than a databse?



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is nine plus seven?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow