Basic PHP, MySQL Login tutorial

Alrighty then, here goes with the first of what I hope will be many tutorials.
This is a BASIC login script that uses a MySQL database to log someone in.

It is by no means a complete, secure, authorising system so please dont come back with things like; “Your session security is rubbish” or “Why isnt this in full OO code?” - It’s a principle tutorial with working code done in a semi OOP/procedural fashion for the purposes of learning.

So here we go, most of the text is in the code - cut, paste and learn :)

1) Database sql file
Create a database or if you have one already just run the following code:

/*
SQLyog Community Edition- MySQL GUI v6.05
Host - 5.1.24-rc-community : Database - spf
*********************************************************************
Server version : 5.1.24-rc-community
*/

/*!40101 SET NAMES utf8 */;

/*!40101 SET SQL_MODE=”*/;

/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=’NO_AUTO_VALUE_ON_ZERO’ */;

/*Table structure for table `members` */

CREATE TABLE `members` (
  `id` int(6) NOT NULL AUTO_INCREMENT COMMENT ‘members id’,
  `username` varchar(12) NOT NULL COMMENT ‘members username’,
  `password` varchar(255) NOT NULL COMMENT ‘members password’,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

/*Data for the table `members` */

insert  into `members`(`id`,`username`,`password`) values (1,’spike’,‘a60e7822190108e7bfa5015a3f57dea1′),(2,‘doug’,‘b07b89b1d596bc0d32cbabed34147efd’);

/*Table structure for table `membersinfo` */

CREATE TABLE `membersinfo` (
  `id` int(12) NOT NULL AUTO_INCREMENT COMMENT ‘record id NOT user’,
  `usr_id` int(6) NOT NULL COMMENT ‘member id’,
  `realname` varchar(255) NOT NULL COMMENT ‘members realname’,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

/*Data for the table `membersinfo` */

insert  into `membersinfo`(`id`,`usr_id`,`realname`) values (1,1,‘Mike’),(2,2,‘Doug’);

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;

The Username/ Password combinations are:
spike/spike
doug/doug

File 1 - functions.php
(remember - comments are in the code!)

<?php

/* Basic login using php and mysql
        ** nothing clever or complicated :)
        ** Build mainly to demonstrate a login system
        ** that anyone can follow
        ** Requirements:
        ** PHP4+/PHP5+
        ** MySQL database
        **
        ** */

/* functions.php
        ** This page is literally for the function that can
        ** be used in the script more than once or need to be
        ** called from different locations eg: login
        ** Also on this page are some basic congiuration items
        ** as this file is included in other pages
        **
        ** session_start();
        ** www.php.net/session_start
        ** Initialize session data
        **
        ** ini_set("display_errors", 2);
        ** ERROR_REPORTING(E_ALL);
        ** set up error reporting
        ** www.php.net/manual/en/function.error-reporting.php
        ** */

       

/* session handler
    ** Start session
    ** append with @ depending on server config */

@session_start();

/* error handler
    ** set error reporting level to 0 to show no error, 2 to show */

ini_set(“display_errors”, 2);
ERROR_REPORTING(E_ALL);

/* define some useful constants
        ** */

define(‘DB_USER’, ‘root’);
define(‘DB_PASS’, ‘peanuts2′);
define(‘DB_HOST’, ‘localhost’);
define(‘DB_BASE’, ’spf’);

/* database connection
        ** connect to your MySQL database
        ** using the constants above.
        **
        ** */

mysql_connect(DB_HOST, DB_USER, DB_PASS);
mysql_select_db(DB_BASE);
               

       
/*————————————->
        function: login form
        ** basic login form
        ** nothing fancy :)
————————————–*/

        function loginForm() {
               
                return
                <fieldset>
                <legend>Please Login</legend>
                        <form name="loginForm" id="loginForm" method="post" action="">
                                <p><label for="usr">Username</label><br />
                                        <input type="text" name="usr" value="" /></p>
                                <p><label for="psw">Password</label><br />
                                        <input type="password" name="psw" value="" /></p>
                                <button type="submit" name="submit" value="SUBMIT">Login</button>
                                <input type="hidden" name="login" value="1">
                        </form>
                </fieldset>
                ‘
;
        }
       
/*————————————->
        function: login process
        ** process the login form
————————————–*/

        function loginProcess($username, $password) {
               
                /* never trust incoming data
                        ** sanitise it and escape it
                        ** basic cleaning 
                        ** mysql_real_escape_string (www.php.net/mysql_real_escape_string)
                        ** trim (www.php.net/trim)
                        ** */

                       
                $username = mysql_real_escape_string(trim($username));
               
                /* using md5 for password security
                        ** if you are using plain password - stop it!
                        ** if you insist on using plain passwords then
                        ** comment/hash the line below
                        ** */

                $password = md5($password);
               
                /* Run the query to find a match in the database
                        ** selecting only the basic fields and
                        ** NOT using *
                        ** also using LIMIT 1 as there should only be one
                        ** result…..
                        ** */

                $sql = mysql_query(
                                select
                                          id
                                        , username
                                        , password
                                from
                                        members
                                where
                                        username = ‘$username’
                                and
                                        password =’$password’
                                limit 1
                        “
);
                       
                /* are there any rows returned
                        ** from the login query?…..
                        ** mysql_num_rows() returns the total number of rows
                        ** found by the query
                        ** So if there is a row
                        ** */

                if(mysql_num_rows($sql) > 0) {
               
                /* assign a results handler to the
                        ** returned fields.
                        ** */

                $rows = mysql_fetch_assoc($sql);
               
                /* register some session variables
                        ** based on the database values */

                $_SESSION[‘usr_logged’] = 1;
                $_SESSION[‘usr_id’] = $rows[‘id’];
                $_SESSION[‘usr_name’] = $rows[‘username’];
               
                /* now that the basic values are registered
                        ** fire them off to the next page
                        ** using header("Location: nextPage.php");
                        ** */

                header(“location: members.php”);
                /* exit() as we dont want the
                        ** script to carry on */

                exit();
                       
                } else {
               
                /* but what happens if there are no results
                        ** returned from the database?
                        ** Make a polite error message
                        ** */

                $errorMsg = ‘<p>Sorry. Your details couldnt be found</p>’;
               
                /* and return that value to the script
                        ** for displaying */

                return $errorMsg;
                }       
               
        }

/*————————————->
        function: check auth
                is the usr_logged variable present?
                has the user logged in? 
————————————–*/

        function checkAuth() {
                /* is the SESSION usr_logged variable
                        ** anywhere? */

                       
                /* if not - redirect them to somewhere they can login
                        **      */
   
                if(!isset($_SESSION[‘usr_logged’])) {
                        header(“Location: index.php”);
                        exit();
                        return false;
                } else {
                /* return true - not really needed but keeps things tidy! */
                        return true;
                }
        }
       

/*————————————->
        function: get member details
                based on the usr_id session variable   
————————————–*/

        function getMemberDetails($id) {
               
                /* query the database using the session usr_id
                        ** variable. Also left join the information table
                        ** to get the extra information
                        ** */

                $sql = mysql_query(
                                select
                                          members.id
                                        , members.username
                                        , members.password
                                        , membersinfo.realname
                                from
                                        members
                                left join
                                        membersinfo
                                on
                                        members.id=membersinfo.usr_id
                                where
                                        members.id = $id                               
                        “
);
               
                /* for this tutorial there are no real details
                        ** but if you had another table with more
                        ** information such as address, postcode etc
                        ** you can use the same theory
                        ** */

               
                /* assign a results handler as we did earlier
                        ** to handle the returning information */

                $rows = mysql_fetch_assoc($sql);
               
                /* note that $rows is an ARRAY and as such holds the
                        ** information like:
                        ** $rows['usrname']
                        ** $rows['password']
                        ** etc… */

                return $rows;
               
        }

?>

File 2 - index.php

<?php
/* include the functions file
        ** so that we can use those functions
        ** */

include(‘functions.php’);

/* set up an empty variable that we can ‘fill’
        ** later in the script.
        ** defining it here avoids the error message…..
        ** Undefined index $whatever on line X….
        ** */

$msg = ;

/* Has the login form been sent?
        ** Check the $_POST global array for the hidden field
        ** Using a hidden field as they will always be sent with a form
        ** whereas the submit button wont always be there if the user hits
        ** enter.
        ** NB: Not sure if that still holds true with modern browsers but its
        ** a habit now :)
        ** */

if(isset($_POST[‘login’])) {
        /* fill the $msg variable that we defined earlier with the
                ** results of the login function */

        $msg = loginProcess($_POST[‘usr’], $_POST[‘psw’]);
}

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

<head>
        <meta http-equiv=“content-type” content=“text/html; charset=iso-8859-1″>
        <title>Index.php</title>
</head>

<body>

<h1>Index</h1>
<?php
/* down to the nitty gritty now!
        ** If the $msg variable is not equal to nothing
        ** then echo it
        ** It should only be full if the login failed…..
        ** */

if($msg != ) {
        echo $msg;
}
/* basic setup…..
        ** check if the session variable usr_logged is present
                ** if it isnt then the user cant have logged in so
                ** give them the login form
                ** */

if(!isset($_SESSION[‘usr_logged’])) {
        echo loginForm();
}

echo md5(‘doug’);

?>
</body>
</html>

file 3 - members.php

<?php
/* include the functions file
        ** so that we can use those functions
        ** */

include(‘functions.php’);

/* USR/MEMBER AUTH CHECK
        ** so this is our members page so we dont want any Tom, Dick or Harry
        ** looking at it so…..
        ** */

checkAuth();
/* if they have got to here, they should be logged in…..
        **/

/* get the member details based on the usr_id held
        ** in the SESSION.
        ** */

$memberDetails = getMemberDetails($_SESSION[‘usr_id’]);

/* if the login form is on this page
        ** process it if it has been sent */

if(isset($_POST[‘login’])) {
        $msg = loginProcess($_POST[‘usr’], $_POST[‘psw’]);
}

/* logging out */
if(isset($_GET[‘logout’])) {
        unset($_SESSION[‘usr_logged’]);
        unset($_SESSION[‘usr_name’]);
       
        header(“Location: index.php”);
        exit();
}
?>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>

<head>
        <meta http-equiv=“content-type” content=“text/html; charset=iso-8859-1″>
        <title>members.php</title>
</head>

<body>

<h1>Members</h1>
<a href=“?logout”>Logout</a>
<?php

echo ‘Welcome back ‘. $_SESSION[‘usr_name’];

/* $memberDetails holds the information returned from the function
        ** that gets all the information from the database
        ** */

echo ‘<p>Members Realname is…. ‘. $memberDetails[‘realname’] .‘</p>’;

?>
<p>That is really all there is to it as a basic, bare bones login system.<br /><br />
It has minimal security so that is something to look at next as is Adding a user to the database.</p>
</body>
</html>

It should be quite easy to follow butif you have any questions, please just ask :)

2 Responses

  1. Extefttop Says:

    It’s amazing

  2. SpikeZ Says:

    just noticed that wordpress does funky things to quotes
    ” is the normal speech mark (SHIFT+2) and ‘ is the single quote ‘

    Spike

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.