Login/Register Platform is very necessary when you need to give your users a special identity on your Website. For developing Login System, MySQL Server is mainly used. Login/Registering System enables a developer to know his visitors and to obtain a very useful Database.

You may have seen many themes of Login Forms, in which mainly CSS is used. Here, I’m going to explain each and every PHP! We have provided you Tutorials with Demo. You may also download the Source Folder directly, here on IQubex. So, now it will surely prove good to start learning…

Let’s Begin

The first step you need to complete is to have a localhost server. The universal fact is, PHP and MySQL never works without add-on softwares on PC like HTML/CSS does. For this, you need to download Xammp or Wamp. If you’re using MAC device, the best one for you is Mamp.

There are special instructions for each of these softwares. So, considering that you have those, lets start for creating a Database. For creating Database, you need to visit localhost/phpmyadmin on your Local Server (Only works after downloading those applications).

For making up a Database, just copy this code and execute it in PhpMyAdmin!

--
-- Database: `subscribers`
--
-- --------------------------------------------------------
--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `userId` int(11) NOT NULL AUTO_INCREMENT,
  `userName` varchar(30) NOT NULL,
  `userEmail` varchar(60) NOT NULL,
  `userPass` varchar(255) NOT NULL,
  PRIMARY KEY (`userId`),
  UNIQUE KEY `userEmail` (`userEmail`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

After this, just execute and then you will be ready with a Database to fill user’s information in it!

Afterwards, we’re going to create the following files in a folder.

  1. dbconnect.php
  2. register.php
  3. index.php
  4. home.php
  5. logout.php

Step 2:

The construction of ‘dbconnect.php’

<?php
error_reporting( ~E_DEPRECATED & ~E_NOTICE );
// Recommended term is PDO or MySQLi to make your login form more secure.

define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '');
define('DBNAME', 'subscribers');

$conn = mysql_connect(DBHOST,DBUSER,DBPASS);
$dbcon = mysql_select_db(DBNAME);

if ( !$conn ) {
die("Connection failed : " . mysql_error());
}

if ( !$dbcon ) {
die("Database Connection failed : " . mysql_error());
}

This will help your login system to connect the Database you created!

Step 3:

The construction of ‘register.php’!

You need to create a new file named ‘register.php’ to proceed. Just write/copy the code given below!

<?php
ob_start();
session_start();
if( isset($_SESSION['user'])!="" ){
header("Location: home.php");
}
include_once 'dbconnect.php';

$error = false;

if ( isset($_POST['btn-signup']) ) {

// clean user inputs to prevent sql injections
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);

$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);

$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);

// basic name validation
if (empty($name)) {
$error = true;
$nameError = "Please enter your full name.";
} else if (strlen($name) < 3) {
$error = true;
$nameError = "Name must have atleat 3 characters.";
} else if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$nameError = "Name must contain alphabets and space.";
}

//basic email validation
if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
} else {
// check email exist or not
$query = "SELECT userEmail FROM users WHERE userEmail='$email'";
$result = mysql_query($query);
$count = mysql_num_rows($result);
if($count!=0){
$error = true;
$emailError = "Provided Email is already in use.";
}
}
// password validation
if (empty($pass)){
$error = true;
$passError = "Please enter password.";
} else if(strlen($pass) < 6) {
$error = true;
$passError = "Password must have atleast 6 characters.";
}

// password encrypt using SHA256();
$password = hash('sha256', $pass);

// if there's no error, continue to signup
if( !$error ) {

$query = "INSERT INTO users(userName,userEmail,userPass) VALUES('$name','$email','$password')";
$res = mysql_query($query);

if ($res) {
$errTyp = "success";
$errMSG = "Successfully registered, you may login now";
unset($name);
unset($email);
unset($pass);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}

}


}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>IQubex Login Demo</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>

<div class="container">

<div id="login-form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

<div class="col-md-12">

<div class="form-group">
<h2 class="">Sign Up.</h2>
</div>

<div class="form-group">
<hr />
</div>

<?php
if ( isset($errMSG) ) {

?>
<div class="form-group">
<div class="alert alert-<?php echo ($errTyp=="success") ? "success" : $errTyp; ?>">
<span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
</div>
</div>
<?php
}
?>

<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
<input type="text" name="name" class="form-control" placeholder="Enter Name" maxlength="50" value="<?php echo $name ?>" />
</div>
<span class="text-danger"><?php echo $nameError; ?></span>
</div>

<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
<input type="email" name="email" class="form-control" placeholder="Enter Your Email" maxlength="40" value="<?php echo $email ?>" />
</div>
<span class="text-danger"><?php echo $emailError; ?></span>
</div>

<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" name="pass" class="form-control" placeholder="Enter Password" maxlength="15" />
</div>
<span class="text-danger"><?php echo $passError; ?></span>
</div>

<div class="form-group">
<hr />
</div>

<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-signup">Sign Up</button>
</div>

<div class="form-group">
<hr />
</div>

<div class="form-group">
<a href="index.php">Sign in Here...</a>
</div>

</div>

</form>
</div>

</div>

</body>
</html>
<?php ob_end_flush(); ?>

This was the script which will help your users to Register on your Database. But, we also need a Login Page to let them Login!

Step 4:

The construction of ‘index.php’!

This is the most necessary page about which everyone has concern. This will let your users see their own Dashboard/Profile. So, just copy this code into ‘index.php’ file.

<?php
ob_start();
session_start();
require_once 'dbconnect.php';

// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: home.php");
exit;
}

$error = false;

if( isset($_POST['btn-login']) ) {

// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);

$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs

if(empty($email)){
$error = true;
$emailError = "Please enter your email address.";
} else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
$error = true;
$emailError = "Please enter valid email address.";
}

if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}

// if there's no error, continue to login
if (!$error) {

$password = hash('sha256', $pass); // password hashing using SHA256

$res=mysql_query("SELECT userId, userName, userPass FROM users WHERE userEmail='$email'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if uname/pass correct it returns must be 1 row

if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['userId'];
header("Location: home.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}

}

}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Coding Cage - Login & Registration System</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>

<div class="container">

<div id="login-form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">

<div class="col-md-12">

<div class="form-group">
<h2 class="">Sign In.</h2>
</div>

<div class="form-group">
<hr />
</div>

<?php
if ( isset($errMSG) ) {

?>
<div class="form-group">
<div class="alert alert-danger">
<span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
</div>
</div>
<?php
}
?>

<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
<input type="email" name="email" class="form-control" placeholder="Your Email" value="<?php echo $email; ?>" maxlength="40" />
</div>
<span class="text-danger"><?php echo $emailError; ?></span>
</div>

<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
<input type="password" name="pass" class="form-control" placeholder="Your Password" maxlength="15" />
</div>
<span class="text-danger"><?php echo $passError; ?></span>
</div>

<div class="form-group">
<hr />
</div>

<div class="form-group">
<button type="submit" class="btn btn-block btn-primary" name="btn-login">Sign In</button>
</div>

<div class="form-group">
<hr />
</div>

<div class="form-group">
<a href="register.php">Sign Up Here...</a>
</div>

</div>

</form>
</div>

</div>

</body>
</html>
<?php ob_end_flush(); ?>

This will let users Login their session, to see their profile/dashboard, or anything else. You may redirect Logged In users anywhere.

Step 5:

Construction of ‘home.php’!

This will be the profile of the Logged In user. You may call it user’s Dashboard or Profile! To make it, just create a file named ‘home.php’ and paste the following code in it!

<?php
ob_start();
session_start();
require_once 'dbconnect.php';

// if session is not set this will redirect to login page
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
// select loggedin users detail
$res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome - <?php echo $userRow['userName']; ?></title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>

<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<span class="glyphicon glyphicon-user"></span>&nbsp;Hi, <?php echo $userRow['userName']; ?>!&nbsp;<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="logout.php?logout"><span class="glyphicon glyphicon-log-out"></span>&nbsp;Sign Out</a></li>
</ul>
</li>
</div>
</nav>

<div id="wrapper">

<div class="container">

<div class="page-header">
<h3>IQubex - The Ultimate Developer's Blog!</h3>
</div>

<div class="row">
<div class="col-lg-12">
<h1>We provide great Knowledge!</h1>
</div>
</div>

</div>

</div>

</body>
</html>
<?php ob_end_flush(); ?>

Yeah! It’s almost done! Now, we just need a Logout feature!

Step 6:

The construction of ‘logout.php’!

This file will add a feature of Logout in your website!

<?php
session_start();
if (!isset($_SESSION['user'])) {
header("Location: index.php");
} else if(isset($_SESSION['user'])!="") {
header("Location: home.php");
}

if (isset($_GET['logout'])) {
unset($_SESSION['user']);
session_unset();
session_destroy();
header("Location: index.php");
exit;
}

If you don’t want it yourself to study this code, you can directly Download the Source Files or you can also See the Demo!

Hurray! We have did it! I hope this worked for you technically. This will help you in lot of tasks. I don’t think, there’s anything left, but still if you think so, please consider commenting about it 🙂

Posted by Kumar Abhirup

Hey guys, Welcome to this fascinating blog IQubex. I'm Kumar Abhirup, a blogger, web designer and a developer from Nasik, the Wine Capital of India! I started IQubex as a hobby and my vision is to make my readers happy and satisfied by answering all their questions on this blog. My age is 13 and I started my developing journey at the age of 10.

One Comment

  1. I have been reading all your articles. But this is what I was looking for. I have gone through some demos for login page but getting some problem each and every try….

    Reply

Don't miss a chance of commenting!