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.

Boone Pickens the social networker? Pickensplan.com launches!

Pickens goes to social networking to promote alternative energy plan

T. Boone Pickens, the legendary billionaire oil tycoon, has developed a rather definitive plan for the United States to become less dependent on foreign oil through alternative energy. Just today Pickens launched the website PickensPlan.com where you find out all the details of his comprehensive energy plan.
What does he see as the principle problem that we face right now? The fact that the United States has become infinitely more dependent on foreign oil. In 1970 we imported 24% of our oil. Today we import 70% and that number is still growing.
What is T. Boone Pickens plan anyway? Pickens believes that the United States should make a huge investment in wind power. He says "the United States is the Saudi Arabia of wind power." The main idea of Pickens plan is that we need to utilize wind power as a major source of U.S. electric power generation. He believes that we can provide electricity to more than 20% of America's homes using wind power within 10 years. The second major step of his plan involves the fact that natural gas is what he calls the "cleanest transportation fuel available today." Pickens believes natural gas, because of its affordability and cleanliness, should be used as a major source of transportation fuel. Natural gas for transportation costs less than $1 now, and 98% of the natural gas used in the United States is from North America. Basically, Pickens believe that through wind electricity and natural gas transportation fuel we can dramatically reduce our need for foreign oil and thus drive down the price of oil.
Pickens is clearly putting on a full court press to push this new energy plan of his. This morning he was a guest on Squawk Box on CNBC to announce the plan. He also had a major articleon his plan today in USA Today. It's not just normal media that Pickens is using though. He has opened a fan club on Facebook and started his own channel on youtube. Pickens is doing this to try to reach younger people and those who he normally couldn't reach.
I think some parts of the plan are a little simplistic. I believe if natural gas is used in a wider way for transportation it will likely cause natural gas prices to soar. Having said this, I believe that Pickens Plan is certainly a step in the right direction. He makes some good clear points about how to ween ourselves off foreign oil, which is clearly what needs to be done. Kudos to Boone Pickens for putting forth a detailed plan!

SERPs - What does this mean?

SERPs - What does this mean?

SERPs is a term commonly seen on internet forums. It is just another piece of jargon that is not quite so mysterious when you know what it stands for. SERP stands for Search Engine Results Page and is used by internet marketers and webmasters to describe where
they appear for their target key words in the various search engines results. This article explains the basics and also details why the results are constantly changing as both the internet and the search engines themselves change.

Blog: http://www.myincomeonline.info/2010/02/serps-what-...

Why is my Browser so Slow?

Photo courtesy CV Neikirk
Photo courtesy CV Neikirk Web Browsers are not the quickest beasts in the computer jungle. Although recent releases of most of the popular browsers are several orders of magnitude faster and more efficent than the lethargic browser suites of earlier desktops, there are still a number of problems that web browsers can have that will have a major impact in both system and browser performance.

A lot of the more popular web pages are quite simply crammed to the edges with Flash, Java, Javascript, blinking ads, eight zillion different fonts, 500K imagemaps with no "bypass this" button, midi files, music, narration, animation and video in dozens of different formats. This is a phenomenal volume of data that would drive quite a number of very capable game engines to their limits. It's understandable that a web browser, which doesn't have "to the metal" access to ultra fast video display memory, the advanced video functions on video cards, or any specialized or optimized functions like game engines do, might have some trouble keeping everything moving at full speed.

But also unlike game engines, most web browsers are equipped with a wide variety of "off switches" many of which make it possible to increase performance dramatically. There are also browsers available for just about every operating system that are both more specialized and faster than standard browsers precisely because they can't do all of the stuff that the larger suites can.

The first and most important potential area for performance slowdowns with a web browser is graphics. The reasons for this are as varied as the individual web sites. Each can have different graphics formats, file sizes, and page layouts. Despite the fact most web connections are on high speed hardware, a page with 50MB of 24-bit non-progressive JPEGs or PNG files is going to be a heavy load for any browser. Browsers are not only limited by download speed, but they have to make room in system memory first, then video memory second for every single one of those files, and that can take a lot of CPU cycles. Again, browsers have to be lowest common denominator applications. They can't have super fast display functions, because they have to support just about any hardware.

The second is animation. Adobe Flash is a great technology and it has done a number of great things for the web, but animation puts a lot of stress on both the CPU and system memory. The doubly difficult part is that Flash animations, even if they are off-screen, can still chew up CPU cycles and extra system memory. Since Flash is almost never the central feature of a web page, it is usually that animated banner ad that is using up a third or more of the CPU cycles that could be put to better use running the rest of the computer.

Third are features that are programmed into web sites using scripting languages like Javascript or compiled virtual machine languages like Java. With a very few notable exceptions, Java is almost always a massively slow addition to any web site. The reason for this is that a browser must load an entire client side virtual machine into memory so a Java program can run. If the virtual machine isn't already in memory this can take several seconds during which time the browser and system may have difficulty doing anything else. Unless it is turned off in advance, a Javascript interpreter is almost always running in most browsers, so it doesn't have the same potential for a system slowdown as Java does. Nevertheless, Javascript can and does slow down web sites, especially poorly written Javascript.

Now the obvious answer would be to simply turn everything off and read the web as a gopher index in 12 point Times New Roman font, but that's really not terribly exciting. The web is supposed to be the future and all. There are ways to increase browser performance, however.

One is to make sure the browser has adequate cache space. Cache is disk memory allocated to a browser so it can keep local copies of pages that have already been visited. This means browsers don't have to re-download information if a page is visited more than once in a given browsing session. The more space that is allocated to cache, the more pages that can be saved client-side and the faster those pages can be re-displayed if visited again.

The second is to turn off any animation or programming language that isn't necessary to the central feature of a given web site. If, for example, you are browsing articles on gardening written in text with a few pictures here and there, having Flash and Java running is unnecessary and will just slow the gardening site down if they have to load an advertisement or something.

Third, and this is important even if performance isn't an issue, is to set your browser to disable pop-ups and pop-unders. Each new window a browser is required to open will reduce the amount of system memory available for quickly displaying web pages. Every pop-up window uses the same amount of memory as a new browser window even if it is only displaying a small ad, and those memory uses can add up as more pop-up windows appear.

The main thing to understand is that web speed isn't just about download speed. What is happening on the client machine can have a dramatic effect on overall performance, and turning off services that aren't needed can make the web faster and more efficient.

 
 
 
 
Copyright © PcBerg