This is a tutorial, specially to guide the PHP beginners, to code a complete Login System. Here we will be learning, Creating Database, posting Form values, creating Session value and then destroying the Session value. It is very useful and simple.
Database Design
Users Table: (This table is made based on our requirements, here we are just including username and password.)
CREATE TABLE users(
uid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) UNIQUE,
password VARCHAR(100));
Adding Data to the Database
Simply add the data to your database, enter atleast 2 rows, with uid (1 and 2) .
db.php
In db.php you must change the SERVER_NAME, USERNAME, PASSWORD and DATABASE to your own MySql settings.
<?php
define('DB_SERVER', 'SERVER_NAME');
define('DB_USERNAME', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_DATABASE', 'DATABASE');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
?>
Index.php
Contains Php and HTML code. It holds the Login form.
<?php
if(isset($_GET["attempt"]))
{
$attempt=$_GET["attempt"];
}
?>
\\Above we check for attempt, whether it is declared in the URL or not.
<div id='login_title'>Curious? Login to WTFD</div>
<div id='login_box'>
<?php
if(isset($attempt))
{
if($attempt == "null")
{
?>
<div><font color="red"><strong>Do not leave any of the field blank.</strong></font></div>
<?php
}
elseif($attempt == "fail")
{
?>
<div><font color="red"><strong>Email and Password do not match, Please try again.</strong></font></div>
<?php
}
}
?>
<form method='post' action='check.php'>
<input type='text' class='input user' placeholder='Username' name='username'/> <br/>
<input type='password' class='input passcode' placeholder='Password' name='password'/> <br/>
<input type='submit' value=' Login ' class='btn' />
</form>
if(isset($_GET["attempt"]))
{
$attempt=$_GET["attempt"];
}
?>
\\Above we check for attempt, whether it is declared in the URL or not.
<div id='login_title'>Curious? Login to WTFD</div>
<div id='login_box'>
<?php
if(isset($attempt))
{
if($attempt == "null")
{
?>
<div><font color="red"><strong>Do not leave any of the field blank.</strong></font></div>
<?php
}
elseif($attempt == "fail")
{
?>
<div><font color="red"><strong>Email and Password do not match, Please try again.</strong></font></div>
<?php
}
}
?>
<form method='post' action='check.php'>
<input type='text' class='input user' placeholder='Username' name='username'/> <br/>
<input type='password' class='input passcode' placeholder='Password' name='password'/> <br/>
<input type='submit' value=' Login ' class='btn' />
</form>
Check.php
Includes Php code to compare Form input values with the database values.
<?php
session_start();
include("db.php");
$username=$_POST['username'];
$password=$_POST['password'];
if(!empty($username) && !empty($password))
//Checking if $username and $password are not empty
{
$command="select * from users WHERE username='$username' and password='$password'";
$result=mysql_query($command);
$count=mysql_num_rows($result);
//In case no matching row is found, count will be zero
if($count==0)
{
header("location:index.php?attempt=fail");
//Send back to index.php with attempt given a value, hence a message is shown on Index page as per its value, null or Fail
}
else
{
$sql="select * from users WHERE username='$username'";
$result=mysql_query($sql);
while($row=mysql_fetch_row($result))
{
$_SESSION["id"]=$row[0];
$_SESSION["username"]=$row[1];
// Creating SESSION for the user
header("location:home.php");
}
}
}
else
{
header("location:index.php?attempt=null");
//This is the case when no value is typed in username or password textbox, null error is shown
}
?>
session_start();
include("db.php");
$username=$_POST['username'];
$password=$_POST['password'];
if(!empty($username) && !empty($password))
//Checking if $username and $password are not empty
{
$command="select * from users WHERE username='$username' and password='$password'";
$result=mysql_query($command);
$count=mysql_num_rows($result);
//In case no matching row is found, count will be zero
if($count==0)
{
header("location:index.php?attempt=fail");
//Send back to index.php with attempt given a value, hence a message is shown on Index page as per its value, null or Fail
}
else
{
$sql="select * from users WHERE username='$username'";
$result=mysql_query($sql);
while($row=mysql_fetch_row($result))
{
$_SESSION["id"]=$row[0];
$_SESSION["username"]=$row[1];
// Creating SESSION for the user
header("location:home.php");
}
}
}
else
{
header("location:index.php?attempt=null");
//This is the case when no value is typed in username or password textbox, null error is shown
}
?>
Home.php
This is the home page, shown after successful login.
<?php
session_start();
if(isSet($_SESSION['id']))
{
$username=$_SESSION['username'];
?>
//Above code is used to restrict user to see this page, untill they are successfully logged in.
<body>
<div><h2>Hello <?php echo $username; ?> you are logged in.</h2></div>
<div><a href='logout.php'>Log Out</a></div>
</body>
<?php
}
else
{
header("location:index.php");
}
?>
session_start();
if(isSet($_SESSION['id']))
{
$username=$_SESSION['username'];
?>
//Above code is used to restrict user to see this page, untill they are successfully logged in.
<body>
<div><h2>Hello <?php echo $username; ?> you are logged in.</h2></div>
<div><a href='logout.php'>Log Out</a></div>
</body>
<?php
}
else
{
header("location:index.php");
}
?>
LogOut.php
To destroy session, and to take the user back to Index page.
<?php
session_start();
session_destroy();
header("location:index.php");
?>
session_start();
session_destroy();
header("location:index.php");
?>
- Index.php is to show the Login Form, Post values from the form to Check.php and also to show error messages based on "attempt" value.
- Check.php is to check the values entered by the user and compare it with the ones stored in database. If matched then direct user to Homepage else show error.
- Home.php is the Homepage and LogOut.php destroys the session and directs user back to the Login page.
If you face any kind of problem in this simple tutorial, feel free to let me know through your comments.

very useful...
ReplyDeletecan you please put a forgot password link in it with simple password sending feature (plaint text passowrd sending on the mail id if the mail id exists in the user table)
$sql= sprintf("SELECT * FROM users WHERE username='%s' AND password='%s'",
ReplyDeletemysql_real_escape_string($username),
mysql_real_escape_string($password));
to escape from SQL Injection attacks, use this.
This code is vulnerable to multiple attack types - the least of which is SQL injection as someone else pointed out. Do not use any of this code in a production environment! You should be using a prepackaged system like:
ReplyDeletehttp://barebonescms.com/documentation/sso/
I have found that system rather easy to use and already use it on a few projects.