« | »

Create a Site Authentication Login with PHP and MySQL

By Studge | May 23, 2007

Setting up restricted access to certain pages is a breeze. Here I will show a quick way to control who can view specific pages using a form based login system and a MySQL database of allowed users.

First we will set up the database table for storing the user login information. We will be encrypting the passwords later on, here is the SQL code for the table:

CREATE TABLE `users` (
  `id` int(4) NOT NULL auto_increment,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM

I insert the users manually through my phpMyAdmin front-end. If I am doing a site that has multiple users, then chances are good that I will be using a content management system, such as Drupal. I use this authentication method for smaller sites and do not find it necessary to write a script for inserting users, but creating one would be relatively simple. The one thing you need to be sure to do when inserting a new user is to select MD5 under the function section for the password (see screenshot below). MD5 is a form of encryption that is easy to implement with PHP.

phpMyAdmin Screenshot

Now we have the MySQL end taken care of and we can focus on securing the pages. For each page that we only want to be seen by authorized eyes, we need to put in some PHP code. I put this code snippet as the first text after the <body> tag. If you are using PHP4, then the code must be the very first text at the top of the web document.

<?php
  session_start();

  if (!isset($_SESSION['is_logged_in'])) {
    header("Location:login.php");
    die();
    }
?>

This snippet checks to see if a user has been authenticated for this session. If not, then the user is redirected to a login form and the script dies. If the user has been authenticated for this session, then the page continues to display the contents. Now we need to create a login page. The code above specifically refers to login.php so we will name the new page just that. Here is my code for the login page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Login</title>
  </head>

  <body>
    <form method="POST" action="check.php">
      Username:<br />
      <input type="text" name="username" />
      <br /><br />
      Password:<br />
      <input type="password" name="password" />
      <br /><br />
      <input type="submit" id="subbut" value="Submit" />
    </form>
  </body>
</html>

You should notice in the above code that the form is posting to a file named check.php. This file will query our previously created MySQL database to verify the user's credentials. Here is how it is coded:

<?php
  session_start();

  if($_SERVER['REQUEST_METHOD'] == "POST") {
    mysql_connect("mysql.example.com", "username", "password");
    @mysql_select_db("database") or die( "Unable to connect to database");
    $username = mysql_real_escape_string($_POST['username']);
    $password = mysql_real_escape_string($_POST['password']);
    $result = mysql_query("SELECT * FROM users WHERE username='$username' AND
      password=md5('$password')");

    if(mysql_num_rows($result) > 0) {
      $_SESSION['is_logged_in'] = 1;
    }
  }

  if(!isset($_SESSION['is_logged_in'])) {
    header("location:login.php");
  } else {
    header("location:authenticated.php");
  }
?>

I have created a page that requires this authentication for you to view, you can visit it here. It is named authenticated.php and that is why the else statement above references that page. It will redirect you to the login.php page unless you have been authenticated. The username and password are user and password respectively. On the authenticated test page you are given to option of logging out. This was done by creating a file named logout.php with the following code:

<?php
  session_start();
  session_destroy();

  header("location:authenticated.php");
?>

That's all there is to it. If you have any questions you can leave a comment or use the contact page and I will get back to you as soon as possible.

Topics: (X)HTML, MySQL, PHP, Web Development

Share: del.icio.us | digg | reddit

RSS feed | Trackback URI

10 Comments »

No comments yet.

Name (required)
E-mail (required - never shown publicly)
URI
Your Comment (smaller size | larger size)
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> in your comment.