ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

User Authentication using PHP and MySQL and web forms

Updated on January 17, 2014

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.

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)