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.

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 a 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 have questions 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(); otherwise 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.

More by this Author


Comments 27 comments

Hawkesdream profile image

Hawkesdream 7 years ago from Cornwall

Think this is way beyond me, sort of understand, I think!

can you say this in picture format lol


rajkishor09 profile image

rajkishor09 7 years ago from Bangalore, Karnataka, INDIA

Rather than using session, i think cookies will do better for "Remember Me" option provided by websites like gmail etc. Because session expires soon , "in case of ASP.Net it expires in 20 min of inactivity", but don't know about PHP.

One more feature I am expecting from you is that when we register an account, page should sent account details to registered e-mail. If you can then please mention how to configure mail server id etc.

Thanks alot.................


Alpho011 profile image

Alpho011 7 years ago from Marietta, Georgia Author

Hawkesdream: I will put up seom screen shots later, but it would have it longer and probably discouraged people.


Alpho011 profile image

Alpho011 7 years ago from Marietta, Georgia Author

rajkishor09 : I used cookies on the remember me function, if you looked at the source files you'll see it, and as far as the mail sent to users, just pop in a simple mail() function along with any account details.

If you have hosted UNIX services your mail configurations should b good to go.

 


rajkishor09 profile image

rajkishor09 7 years ago from Bangalore, Karnataka, INDIA

sorry i could not see cookie that time, i apologies..........


PHP Authentication 7 years ago

Nice post, most people forget to address the SQL injection attacks. However, storing plain text passwords in database (especially in cookies!) is not advisable. You should store one-way hash values of passwords instead.


DaiLaughing 7 years ago

I can't see screenshots helping much but maybe a bit of indenting and even colour coding. The main point though has been made already - password encryption.


psychicdog.net profile image

psychicdog.net 7 years ago

Really enjoy your stuff Alpho011.

Thanks again for a great read!

Forms seems to be one of those unavoidables. For what it's worth, check out the form at CodeIdol.com I adapted it for registration on one of my sites. It uses  ($_SERVER['REQUEST_METHOD'] == 'GET') {  display the form if the request is a GET    } else {    // if the  request is a POST, validates the form using error array with key for each type of error ex.: invalid email,nonmatching pwds etc...

Really interesting...not often do you see the REQUEST METHOD USED and cylcing thru an array of errors. It was the first time I'd come across this technique anyway and it worked a treat.   


John 7 years ago

Very well written php ... keep up the good work ....


Aya Katz profile image

Aya Katz 7 years ago from The Ozarks

Thanks for this informative hub!


zero7web profile image

zero7web 6 years ago from Manchester, UK

Your post variables are not adequately cleaned in this script but i appreciate it's a basic guide to get people started. Well done


bianca 6 years ago

i think that your function is too large...,is good that u explained step by step :)


Pravin 6 years ago


showw 6 years ago

Hawkesdream: I will put up seom screen shots later, but it would have it longer and probably discouraged people!!!


Afsal Rahim profile image

Afsal Rahim 6 years ago from India

Informative. But its really foolish to store passwords as plain text in database. Store as hashed passwords, use md5 and other technique like salt to make it more secure.


Freelance PHP Developer 6 years ago

anyway thanks. i was stuck with user authentication module on my academic project. it could helped me.


u307911 5 years ago

This is what I'm getting in the browser based on the above:

User Name:

Password: ******************

Remember Me: Submit Button

Any to relist all the php forms again?


Eric 5 years ago

Does someone still has the source files. The zip files are no longer available

thanks in advance


plusones profile image

plusones 5 years ago from UK

I have tried making my own user authentication for a few projects and found myself reverting to Wordpress. Install a decent plugin like S2Members and then make pages for different levels of users. Its so much easier to use and extend plus its easy


Jennie Demario profile image

Jennie Demario 5 years ago from Floating in the clouds

I noticed that your script uses mysql_real_escape_string. Do you feel that there is a difference as far as mysql injections or other security vulnerabilities while using mysql_real_escape_string versus add slashes? I have already developed scripts using add slashes and I am not sure if it would be worth it to back track and change it up.


bigoyaseo profile image

bigoyaseo 5 years ago from New Delhi

benefits of using php as development language at http://www.akritisoftwares.com


pankaj 4 years ago

not bad


d;kjaf 4 years ago

rgfdg


vaigundaraja 4 years ago

login athuendication post me please


ako 4 years ago

galing


jacharless profile image

jacharless 4 years ago from Between New York and London

Nice script.

A bit bloated for my taste, but nice.

Question regarding the "heavy" elements for the $_SESSION. That is a lot to hold in queue while the user is logged in/idle. Also, are enough cleaners for a cookie & session destroy?

I found that passing the IPA of the machine works much faster and allows lots of flexibility, script wise.

Voted Up! ~James


larder418 4 years ago

Any person on here know about them?

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working