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.='<span>Attempts Left[' . $remainLogins . ']</span>';
$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:
<?php include 'funt.php';?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
logOn();
?>
</body>
</html>
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:
<div id="userNameWrap">
<form id="loginFrm" name="loginFrm" action="<?=$_SERVER['PHP_SELF'];?>?cmd=lg" method="post">
<h4><?=$errorMess;?></h4>
<div class="userNameRow">
<span class="userClassLeft">User Name:</span><span class="userClassRight"><input name="userName" type="text" class="<?=$aClass;?>" id="userName" value="<? if (!isset($_COOKIE['remMe'])){ echo $_POST['userName'];} else { echo $_COOKIE['remMe']; }?>" size="28" />
</span>
</div>
<div class="userNameRow">
<span class="userClassLeft">Password:</span><span class="userClassRight"><input name="passWord" type="password" class="<?=$aClass;?>" id="passWord" value="<? if (!isset($_COOKIE['remPass'])){ echo $_POST['passWord'];} else { echo $_COOKIE['remPass']; }?>" size="28" />
</span>
</div>
<div class="userNameRow">
<span class="userClassLeft">Remember Me:</span><span class="userClassRight"><input name="remMe" type="checkbox" id="remMe" value="1" <?php if(isset($_COOKIE['remMe'])){?>checked<?php } ?>/>
</span>
<input class="blueButtonBgClass" name="Submit" type="Submit" value="Submit" />
</div>
<div class="userNameRow">
<div align="center"></div>
</div>
</form>
</div>
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.
<?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.
User Authentication using PHP and MySQL and web forms
Labels: event calender
blog comments powered by Disqus