How to Secure PHP Sessions With MySQL Passwords

When a user runs a PHP application, you can create a PHP session for that user. The session gives you the ability to define variables and store data specific to that user session that can be accessed across multiple webpages. PHP sessions are typically used in conjunction with the requirement that a user log in to an application. You can create this functionality with an HTML form and a MySQL database that stores usernames and passwords. When you do this, you are securing the PHP session with passwords stored in a MySQL database.

Instructions

  1. Create the MySQL Database

    • 1

      Create a new MySQL database to house the table of username and password combinations. For example, sign in to MySQL at the command line and type:

      CREATE DATABASE `security` DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

    • 2

      Create the MySQL table to store a username and password for each user. For example, at the command line type:

      CREATE TABLE `security`.`users` (

      `id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,

      `username` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL ,

      `password` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL ,

      PRIMARY KEY ( `id` )

      ) ENGINE = MYISAM;

    • 3

      Populate the table with at least one initial entry for the administrative user. Use the "md5" function to encrypt the password before storing it in the database. For example, at the command line type:

      INSERT INTO `security`.`users` (`id`, `username`, `password`) VALUES (NULL, "admin", md5("Password3*"));

    Create and Display the Login Form

    • 4

      Create a new PHP file using an HTML editor or Notepad that will present a login form to the user, determine if the username and password are correct and direct the user to the URL saved in a session variable called "nexturl." Begin a PHP session and check a session variable to determine if the user is already logged in or initialize the session variable. For example, in the editor type:

      <?php

      session_start();

      if (!isset($_SESSION['authorized'])) $_SESSION['authorized'] = false;

      if ($_SESSION['authorized'] === true) header("Location: " . $_SESSION['nexturl']); //already logged in

    • 5

      Get the username and password from the login form or set them to null if the form has not yet been processed. For example, in the editor type:

      $username = $_POST['username'] || "";

      $password = $_POST['password'] || "";

      ?>

    • 6

      Present an HTML login form to the user. Set the action to the PHP file with the form using "PHP_SELF" and set the form method to "post." For example, in the editor type:

      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

      <html>

      <head>

      <title>Login</title>

      <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

      </head>

      <body>

      <form action="<?php echo htmlentities($_SERVER[PHP_SELF]); ?>" method="post">

      <fieldset><legend>Login</legend>

      <strong>Username: </strong><input type="text" width="30" name="username" value="<?php echo $username; ?>" /><br/>

      <strong>Password: </strong><input type="password" width="30" name="password" value="<?php echo $password; ?>"/>

      <input type="submit" name="submit" value="Login" />

      </fieldset>

      </form>

    • 7

      Check that the username and password variables are defined or exit and wait for the user to fill in the form. For example, in the editor type:

      if ($username == "" || $password == "") return;

    Validate the User Login With MySQL

    • 8

      Open the MySQL database and select the table with the username and password data. For example, in the editor type:

      $dbc = @mysql_connect("localhost", "username", "password") || die("Cannot open security database!");

      $db = @mysql_select_db("users") || die("Cannot open security table!");

    • 9

      Create a query to return the database record that matches the username and password provided. Use the "md5" function to encrypt the password so it is in the same format as stored in the database. Escape all user input fields with "mysql_real_escape_string" to prevent SQL injections. For example, in the editor type:

      $query = sprintf('SELECT * FROM users WHERE username="%s AND password="%s', mysql_real_escape_string($username), mysql_real_escape_string(md5($password)));

    • 10

      Run the query on the database and evaluate the result. Reject the login if the query fails or if no records were returned. For example, in the editor type:

      $result = mysql_query($query);

      if (!$result || mysql_num_rows($result) != 1) {

      echo '<p class="error">Invalid login!</p>';

      return;

      }

    • 11

      Redirect the user to the URL stored in the "nexturl" session variable if the login was successful. For example, in the editor type:

      header("Location: " . $_SESSION['nexturl']);

      ?>

      </body>

      </html>

Tips & Warnings

  • For security reasons, you should not store passwords in plain text in the database. Use a function such as "md5" to encrypt a password and store the encrypted value in the database. You cannot decrypt a password encrypted with "md5."

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured