PHP User Authentication

By Paulus, 31 January, 2008

The Tables

First we're going to need a table to hold the user information. I've done a very basic table, you can expand this table to include the user's name, e-mail address, street address, etc.

CREATE TABLE TblUsers(
user_id VARCHAR(18) NOT NULL PRIMARY KEY,
user_password VARCHAR(255) NOT NULL,
question TEXT NOT NULL,
q_answer TEXT NOT NULL,
CONSTRAINT user_id_fk FOREIGN KEY(user_id)
REFERENCES TblPermissions(user_id));

For the sake that I can, in the event that you want to limit users to perform certain tasks you can create another table for permissions:

CREATE TABLE TblPermissions(
user_id VARCHAR(18) NOT NULL PRIMARY KEY,
perm_one INT NOT NULL DEFAULT 0 CHECK( perm_one < 1 && perm_one > 0 ),
perm_two INT NOT NULL DEFAULT 0 CHECK( perm_two < 1 && perm_two > 0 )
);

I kept this table simple. Obviously, if you wanted to you could definitely add more permissions depending on how big your application or site is. I will explain this in a later entry. We're going to need a place for the user to log in. In order for the user to login and remain logged in, we're going to have to start a session:

session_start();
Now we must undo what magic quotes does. If magic quotes is enabled, this will undo everything that it did.

if( get_magic_quotes_gpc()) {
$_REQUEST = array_map('stripslashes', $_REQUEST);
$_COOKIE = array_map('stripslashes', $_COOKIE);
}

We're going to need at least three files for the user to login, do some work, then log out. Again, you can definitely have more pages depending on what you're trying to acomplish.

The login page is a very basic page where the person is going to put in their credentials. Behind the scenes the page will submit the data to itself and verify that the user is a valid user. After it determines that the person trying to gain access is valid, it will foreword the user to the second page, which is called main.php in this example.

When storing passwords in a database, it's important to encrypt them. NEVER store them in plain text!! The query that we'd use in this case to create a user would be:

INSERT INTO TblUsers(user_id, user_password, question, q_answer) VALUES('test', PASSWORD('password'), 'Where was I born?', 'New York City');

Now, if you wrote a page to add users, the query would look like:

$query = "INSERT INTO TblUsers(user_id, user_password, question, q_answer) VALUES('" . mysql_real_escape_string($_REQUEST["UserID"] . "', '" . mysql_real_escape_string($_REQUEST["UserPWD"] . "', '" . mysql_real_escape_string($_REQUEST["UserQuestion"] . "', '" . mysql_real_escape_string($_REQUEST["UserAnswer"] . "')";

The mysql_real_escape_string function is to ensure that the user isn't putting any evil data into the field that would result in data being exposed.

That's it! If you want, you can download the files that were used in this entry: