Login Script with Validation

David Carr

Tutorials PHP & MySQL

A login script tutorial to log users into your database driven site using sessions. The database structure I'll be using in this example is below. 

CREATE TABLE IF NOT EXISTS `members` (
`memberID` int(11) NOT NULL auto_increment,
`username` varchar(50) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`memberID`)
) ENGINE=MyISAM;

Make a connection to the database.

//start the session
session_start();

// db properties
$dbhost = 'localhost';
$dbuser = 'database username';
$dbpass = 'database password';
$dbname = 'database name';

// make a connection to mysql here
$conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error());

mysql_select_db ($dbname) or die ("I cannot select the database '$dbname' because: " . mysql_error());

Once you've set-up the table to be used you can move onto the login script. First I create a function that will log the user in. If the login details are not correct the user will got en error message saying wrong username or password. If the login is successful then a session is created to store the user id (which can then be used later for your other scripts) then the form is hidden and you would show what ever it is a logged in user would see.

Lets start with the login function first you define a function using the command function then pass two parameters to it in this case $user and $pass which are the username and password entered in the login form.

//log user in ---------------------------------------------------
function login($user, $pass){

Now I add the data passed in the function to variables then form was sent using post so I will get the data by using $_POST['fieldname']

I am also using the command trim to remove any white space before or after the data, Then add the data to the variables.

//get data from form
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);

Next I strip any tags that a user may have posted using the command strip_tags() 

//strip all tags from variable
$user = strip_tags($user);
$pass = strip_tags($pass);

Then escape all data to make it safe for a MySQL query this protects against MySQL injection attacks, using mysql_real_escape_string()

// escape all data in variables to prevent mysql injection
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);

Now encrypt the password I'm using MD5 to encrypt the password. MD5 is a one way encryption so once it's been set it cannot be reversed. Note the password needs to already be encrypted in the database for this to work.

$pass = md5($pass);

Next query the database to check the username and password given are correct by selecting the username from the required table where username is $user and password is $pass if their is a problem with query print out an error using or die with the command mysql_error().

// check if the user id and password combination exist in database
$sql = "SELECT username FROM members WHERE username = '$user' AND password = '$pass'";
$result = mysql_query($sql) or die('Query failed. ' . mysql_error());

Then check so see their is a match get the number of row by using mysql_num_rows() then perform an if statement if the number of rows is equal to 1 then there is a match otherwise the else statement is executed.

Now the memberID is needed from the database so using the $user variable do a MySQL query then assign the memberID to a variable.

Then create a session by using the command $_SESSION[] give the session a name that will be unique then add the memberID varible to it to store the memberID in the session.

if (mysql_num_rows($result) == 1) {
  // the username and password match, set the session
  //get the memberID from database
  $getid = mysql_query("SELECT * FROM members WHERE username = '$user'");

 while($row = mysql_fetch_object($getid)){
  //assign memberID to a variable
  $memberID = $row->memberID;

  //set the session
  $_SESSION['isloggedin'] = $memberID;
 }

Next we reload the page using header() set the location to $_SERVER['HTTP_REFERER'] as this will reload the current page then use exit; to make sure the script ends there.

// reload the page
header('Location: '.$_SERVER['HTTP_REFERER']);
exit;

<p>if the username and password are not a match then the else statement is run a error message is assigned to variable then above that add global to the error message this enables you can call this variable outside the function.</p>

} else {
//make error message available outside of function

global $errorMessage;
// define an error message
$errorMessage = '<p>Sorry, wrong username or password</p>';
}
}
//end of function

Then check to see if the session is not set by using the not operator ! and isset if the session is not set then show the login form.

if (!isset($_SESSION['isloggedin'])){

Then you have a basic form the form's action is set to $_SERVER['PHP_SELF'] this will reload the same page and the form's method is set to post. notice the name of the submit field slogin this will call the login function when the form is submitted.

<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<p>Login: Username<input name="user" type="text" size="10" />
Password<input type="password" name="pass" size="10" />
<input type="submit" name="slogin" value="Login" /></p>
</form>

Check if the form has been submitted by using if isset $_POST['slogin'] (which is the name of the submit button) then call the login function with two parameters: $user and $pass.

}
if (isset($_POST['slogin'])){
login($user, $pass);
}

If the login failed then print out an error message

//if login failed

if (isset($errorMessage)) {
echo "<p><span class="warning">$errorMessage</span></p>n";
}

Here's the full script

<?php
//start the session
session_start();

// db properties
$dbhost = 'localhost';
$dbuser = 'database username';
$dbpass = 'database password';
$dbname = 'database name';

// make a connection to mysql here
$conn = mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error());
mysql_select_db ($dbname) or die ("I cannot select the database '$dbname' because: " . mysql_error());

//log user in ---------------------------------------------------
function login($user, $pass){

//get data from form
$user = trim($_POST['user']);
$pass = trim($_POST['pass']);

//strip all tags from variable
$user = strip_tags($user);
$pass = strip_tags($pass);

// escape all data in variables to prevent mysql injection
$user = mysql_real_escape_string($user);
$pass = mysql_real_escape_string($pass);
$pass = md5($pass);

// check if the user id and password combination exist in database
$sql = "SELECT username FROM members WHERE username = '$user' AND password = '$pass'";
$result = mysql_query($sql) or die('Query failed. ' . mysql_error());

if (mysql_num_rows($result) == 1) {

// the username and password match,
// set the session
//get the memberID from database

$getid = mysql_query("SELECT * FROM members WHERE username = '$user'");

while($row = mysql_fetch_object($getid)){

//assign memberID to a variable
$memberID = $row->memberID;
//set the session
$_SESSION['isloggedin'] = $memberID;
}

// reload the page
header('Location: '.$_SERVER['HTTP_REFERER']);
exit;

} else {
//make error message avalible outside of function
global $errorMessage;
// define an error message

$errorMessage = '<p>Sorry, wrong username or password</p>';

}
}
?>
<?php

if (!isset($_SESSION['isloggedin'])){
?>

<form action="<?php $_SERVER['PHP_SELF'];?>" method="post">
<p>Login: Username
<input name="user" type="text" size="10" />
Password
<input type="password" name="pass" size="10" />
<input type="submit" name="slogin" value="Login" />
</p>
</form>
<?php
}

if (isset($_POST['slogin'])){
login($user, $pass);
}

//if login failed
if (isset($errorMessage)) {
echo "<p><span class="warning">$errorMessage</span></p>n";
}

That's all there is to creating a basic login script. Note to destroy the session and log a user out use unset($_SESSION['isloggedin']);

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Fathom Analytics $10 discount on your first invoice using this link

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.