User Authentication using PHP and MySQL and web forms

User Authentication using PHP , MySQL and a web form

This is a how to on establishing a login system for a web page or web based application.

Source files

You've seen them, account signups, email etc, well we are going to show the gist of a PHP login system using MySQL for user management.

First lets create a database responsible for managing the users

CREATE TABLE IF NOT EXISTS `regUserTbl` (
`regUserID` int(11) NOT NULL auto_increment,
`regUserName` varchar(50) NOT NULL,
`regPassWord` varchar(100) NOT NULL,
`regFirstName` varchar(50) NOT NULL,
`regLastName` varchar(25) NOT NULL,
`regEmail` varchar(75) NOT NULL,
`regPhone` varchar(13) NOT NULL,
`regVerified` tinyint(1) NOT NULL,
`regToken` varchar(100) NOT NULL,
`regStamp` datetime NOT NULL,
`regLastLog` datetime NOT NULL,
PRIMARY KEY (`regUserID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='Registered users table' AUTO_INCREMENT=1;

Run the above through a SQL query window through your favorite DBMS, i.e. PhpMyAdmin.

Upon success we are ready to go.

Here are the basics.

   1. The page needs to be secure from persons not logged in
   2. The page needs to redirect to the login page if not logged in
   3. The other outstanding logic is that the page shows the form if the Submit button is not clicked, and if it is clicked it checks for the form (validates) the info before we start querying the database (important).

The easiest way to do this is to create a function that will handle all of the processing and then just call the function (neat and tidy).

Lets create a page called login.php (I know really creative).

Now lets create a page called funt.php, this page will carry all of the functions we need and use on all pages.

In the funt.php, first make sure if using a WYSIWIG remove all auto code, just make sure the page is blank.

After that copy and paste this:

function logOn(){
//remove this after maintenance
//$errorMess = 'Performing Maintenance, Try again later!';
//include $_SERVER['DOCUMENT_ROOT'] . '/form/loginFrm.php';
//return;
if(!isset($_POST['Submit'])){
if(!isset($_COOKIE['remMe']) && !isset($_COOKIE['remPass'])){
$errorMess = 'Please Log in your Account!';
}else{
$errorMess = 'Welcome Back: ' . $_COOKIE['remUser'] . '!';
}
$aClass = 'normFormClass';
include $_SERVER['DOCUMENT_ROOT'] . '/gfl/form/loginFrm.php';
}elseif(isset($_POST['Submit'])){
//clean the strings for injection
$userName = mysql_real_escape_string($_POST['userName']);
$passWord = mysql_real_escape_string($_POST['passWord']);
//empty vars
#################################
### Error Checking ##############
if(empty($userName) && empty($passWord)){
$errorMess = 'Put in Username and Password!';
$aClass = 'errorFormClass' ;
include $_SERVER['DOCUMENT_ROOT'] . '/gfl/form/loginFrm.php';
}elseif(empty($userName)){
$errorMess = 'Put in Username';
$aClass = 'errorFormClass';
include $_SERVER['DOCUMENT_ROOT'] . '/gfl/form/loginFrm.php';
}elseif(empty($passWord)){
$errorMess = 'Put in Password';
$aClass = 'errorFormClass';
include $_SERVER['DOCUMENT_ROOT'] . '/gfl/form/loginFrm.php';
}else{
//logon part of the function
$matchSql ="select * from regUserTbl";
$matchSql.=" where regUserName = '" . $userName . "'";
$matchSql.=" and regPassWord = '" . $passWord . "'";
$matchSql.=" and regVerified = '0'";
$matchResult = mysql_query($matchSql);
$matchNumRows = mysql_num_rows($matchResult);
if($matchNumRows == 1){
$errorMess = 'Check Email For Instructions on Verification!';
$aClass = 'errorFormClass';
include $_SERVER['DOCUMENT_ROOT'] . '/gfl/form/loginFrm.php';
}else{
//select statement
$sql ="select * from regUserTbl";
$sql.=" where regUserName = '" . $userName . "'";
$sql.=" and regPassWord = '" . $passWord . "'";
$sql.=" and regVerified = '1'";
$totalLogins = 3;
//run the results
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
//if no match put out and error
if($userName != $row['regUserName'] && $passWord != $row['regPassWord']){
if(!isset($_SESSION['attempLog'])){
$_SESSION['attempLog'] = 1;
//echo 'empty';
}elseif(isset($_SESSION['attempLog'])){
//$_SESSION['attempLog'] = $_POST['att']++;
$_SESSION['attempLog']++;
if($_SESSION['attempLog'] == 3){
//echo 'really full';
unset($_SESSION['attempLog']);
$errorMess = 'Recover Lost Password!';
$aClass = 'errorFormClass' ;
include $_SERVER['DOCUMENT_ROOT'] . '/gfl/form/lostPass.php';
return;
}
}
//count the login attempts
$remainLogins = $totalLogins - $_SESSION['attempLog'];
$errorMess = 'No Matches';
//$errorMess.='&ltspan&gtAttempts Left[' . $remainLogins . ']&lt/span&gt';
$aClass = 'errorFormClass' ;
include $_SERVER['DOCUMENT_ROOT'] . '/gfl/form/loginFrm.php';
//echo $_SESSION['attempLog'];
#######################################
### end of Error Checking
#######################################
}else{
//create cookie for future logins
if($_POST['remMe'] == 1){
setcookie('remMe' , $_POST['userName'], time()+604800);
setcookie('remPass' , $_POST['passWord'], time()+604800);
setcookie('remUser' , $row['regFirstName'], time()+604800);
//echo 'setcookie';
//return;
}elseif(empty($_POST['remMe'])){
setcookie('remMe' , $_POST['userName'], time()-604800);
setcookie('remPass' , $_POST['passWord'], time()-604800);
setcookie('remUser' , $row['regFirstName'], time()-604800);
}
$_SESSION['userId'] = $row['regUserID'];
$_SESSION['userName'] = $row['regUserName'];
$_SESSION['passWord'] = $row['regPassWord'];
$_SESSION['firstName'] = $row['regFirstName'];
$_SESSION['lastName'] = $row['regLastName'];
//show all the account info
header('location: main.php?cmd=ac');
}//end else
}//end elseif
}
}
}//end function

This is the function that will do all the damage we need.

login.php

Create a simple web page like so:

&lt?php include 'funt.php';?&gt

&lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt
&lthtml xmlns="http://www.w3.org/1999/xhtml"&gt
&lthead&gt
&ltmeta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt
&lttitle&gtUntitled Document&lt/title&gt
&lt/head&gt

&ltbody&gt

&lt?php

logOn();
?&gt

&lt/body&gt
&lt/html&gt

Notice in bold, we have included the funct.php, and we are calling the login function that we've  created, relax the function will do all the work, and can do more if we choose to.

The first thing the function does is look to see if the Submit button is clicked, if it were submitted already, the form will submit itself.

if(!isset($_POST['Submit'])){
if(!isset($_COOKIE['remMe']) && !isset($_COOKIE['remPass'])){
$errorMess = 'Please Log in your Account!';
}else{
$errorMess = 'Welcome Back: ' . $_COOKIE['remUser'] . '!';
}
$aClass = 'normFormClass';
include $_SERVER['DOCUMENT_ROOT'] . '/gfl/form/loginFrm.php';

OK, we got a couple of things going on here, we are using a conditional statement to select an user message built into the form.

Before we go any further here is the form code:

&ltdiv id="userNameWrap"&gt
&ltform id="loginFrm" name="loginFrm" action="&lt?=$_SERVER['PHP_SELF'];?&gt?cmd=lg" method="post"&gt
&lth4&gt&lt?=$errorMess;?&gt&lt/h4&gt
&ltdiv class="userNameRow"&gt
&ltspan class="userClassLeft"&gtUser Name:&lt/span&gt&ltspan class="userClassRight"&gt&ltinput name="userName" type="text" class="&lt?=$aClass;?&gt" id="userName" value="&lt? if (!isset($_COOKIE['remMe'])){ echo $_POST['userName'];} else { echo $_COOKIE['remMe']; }?&gt" size="28" /&gt
&lt/span&gt
&lt/div&gt
&ltdiv class="userNameRow"&gt
&ltspan class="userClassLeft"&gtPassword:&lt/span&gt&ltspan class="userClassRight"&gt&ltinput name="passWord" type="password" class="&lt?=$aClass;?&gt" id="passWord" value="&lt? if (!isset($_COOKIE['remPass'])){ echo $_POST['passWord'];} else { echo $_COOKIE['remPass']; }?&gt" size="28" /&gt
&lt/span&gt
&lt/div&gt
&ltdiv class="userNameRow"&gt
&ltspan class="userClassLeft"&gtRemember Me:&lt/span&gt&ltspan class="userClassRight"&gt&ltinput name="remMe" type="checkbox" id="remMe" value="1" &lt?php if(isset($_COOKIE['remMe'])){?&gtchecked&lt?php } ?&gt/&gt
&lt/span&gt
&ltinput class="blueButtonBgClass" name="Submit" type="Submit" value="Submit" /&gt
&lt/div&gt
&ltdiv class="userNameRow"&gt
&ltdiv align="center"&gt&lt/div&gt
&lt/div&gt
&lt/form&gt
&lt/div&gt

There are some things going on the form code you may ?'s about, post them and I will be happy to oblige.

Notice at the top of the form code $errorMess, we use this variable to give feedback to our users, (bad login, etc).

Now here is what happens when we push the button:

}elseif(isset($_POST['Submit'])){

First things first:

//clean the strings for injection
$userName = mysql_real_escape_string($_POST['userName']);
$passWord = mysql_real_escape_string($_POST['passWord']);

And then we check for empty fields:

//empty vars
#################################
### Error Checking ##############
if(empty($userName) && empty($passWord)){
$errorMess = 'Put in Username and Password!';
$aClass = 'errorFormClass' ;
include $_SERVER['DOCUMENT_ROOT'] . '/gfl/form/loginFrm.php';
}elseif(empty($userName)){
$errorMess = 'Put in Username';
$aClass = 'errorFormClass';
include $_SERVER['DOCUMENT_ROOT'] . '/gfl/form/loginFrm.php';
}elseif(empty($passWord)){
$errorMess = 'Put in Password';
$aClass = 'errorFormClass';
include $_SERVER['DOCUMENT_ROOT'] . '/gfl/form/loginFrm.php';

if you look thru each case, you can follow the logic, if you didn't fill out a field, show the form, simple.

Now here is what happens when all fields are present and accounted for:

$sql ="select * from regUserTbl";
$sql.=" where regUserName = '" . $userName . "'";
$sql.=" and regPassWord = '" . $passWord . "'";
$sql.=" and regVerified = '1'";

We are checking to see if we carry any matches against the db.

You know what happens when you answer the door and you don't know the person right, well you don't let them in, same thing except in outer space now.

//if no match put out and error
if($userName != $row['regUserName'] && $passWord != $row['regPassWord']){

And of course we show the form, the point is not to allow the person access and when we don't we SHOW the form.

Alot of people ask ok the login is working, what do I do next, you show them the PAGE, we redirect after all is well.

Before that we created all the SESSION vars we need to make the magic work.

$_SESSION['userId'] = $row['regUserID'];
$_SESSION['userName'] = $row['regUserName'];
$_SESSION['passWord'] = $row['regPassWord'];
$_SESSION['firstName'] = $row['regFirstName'];
$_SESSION['lastName'] = $row['regLastName'];
//show all the account info
header('location: lockedPage.php');

Notice in bold, first we create some sessions and then we send the user to the page, which in our example lockedPage.php.

That's the gist of it, a couple of tidbits though, the lockedPage.php must have a couple of deals at the top the page in order for this thing to pull off.

&lt?php

session_start();

if(empty($_SESSION['userId'])){

// send them back to login

header('location: login.php');

}

We must always start our pages using session_start(); other wise the values will not be carried over in the new page, and the conditional statement does what is says, if the SESSION does not exists, send them back (SHOW THEM THE FORM).

Now if there any questions or needs lets post them and share, as always take it and make it better so we can all learn, and always look for more efficient and elegant ways to make it happen, thank you all.

blog comments powered by Disqus
 
 
 
 
Copyright © PcBerg