PHP Login and Registration Script: User Login/registration system is one of the key components of any membership driven websites and the ability to build them is a must have skill for any web developer. In this post, let us see how to create a complete login and registration system using php and mysql database.
This tutorial is fairly simple and easy to understand, but it covers as much as required to build advanced login/registration system - right from data validation to maintaining php sessions for authenticated access.
MySQL Database for Login/Registration Module
Before entering into the coding part, first let us build the database required for this example.
Read Also:- Country State City Dropdown List using jQuery, Ajax & PHP
- Simple AJAX Pagination Script in jQuery, PHP PDO & MySQL
- File Upload, View and Download using PHP and MySQL
CREATE DATABASE `testdb`;
USE `testdb`;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`email` varchar(60) NOT NULL,
`password` varchar(40) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Run this sql file in phpmyadmin interface and create the database and table.
PHP Script for Login and Registration System
To build the login/registration system we need to create the following files.
- index.php - This is the home page of our application
- register.php - It contains the user sign up form
- login.php - It contains the login form
- logout.php - This contains the user logout script
- dbconnect.php - MySQL database connection script
System Flow for User Login Registration Module
These are the steps breakdown of the user registration/login module we are going to build.
- The Home page (index.php) contains links for login and sign up process in top navigation menu.
- For new users » click on sigup link » user redirected to registration form » fill up the form and submit » validate the form input » registration succeed » notify user and redirect to login page.
- For registered users » click on login link on index.php » user redirected to login page » user provide login credentials » authenticate user and redirect to index page.
- For signed in users » show user's name and logout link on navigation bar.
- User clicks on logout » delete user details from session variable and destroy session » redirect to Home page.
Note: This tutorial uses twitter bootstrap framework for css. I prefer to use this as it's readily available and you can easily integrate bootstrap with HTML. But if you prefer custom style sheet then you can simply attach one and replace all the class selectors used in the html tags with your own. However the program functionality remains the same and will not be disturbed.
Dbconnect.php
This is where we connect to the mysql database. Keeping database connectivity in a separate file is very handy. This way you can get access to database across multiple files by simply including the file once and access it anywhere.
<?php
//connect to mysql database
$con = mysqli_connect("localhost", "myusername", "mypassword", "testdb") or die("Error " . mysqli_error($con));
?>
Register.php
This php file contains the code for the user registration process. The access to this page will be restricted for signed in user. We do this by checking out the session variable.
<?php
session_start();
if(isset($_SESSION['usr_id'])) {
header("Location: index.php");
}
include_once 'dbconnect.php';
//set validation error flag as false
$error = false;
//check if form is submitted
if (isset($_POST['signup'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);
//name can contain only alpha characters and space
if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
$error = true;
$name_error = "Name must contain only alphabets and space";
}
if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
$error = true;
$email_error = "Please Enter Valid Email ID";
}
if(strlen($password) < 6) {
$error = true;
$password_error = "Password must be minimum of 6 characters";
}
if($password != $cpassword) {
$error = true;
$cpassword_error = "Password and Confirm Password doesn't match";
}
if (!$error) {
if(mysqli_query($con, "INSERT INTO users(name,email,password) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
$successmsg = "Successfully Registered! <a href='login.php'>Click here to Login</a>";
} else {
$errormsg = "Error in registering...Please try again later!";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Registration Script</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport" >
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<!-- add header -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php">Koding Made Simple</a>
</div>
<!-- menu items -->
<div class="collapse navbar-collapse" id="navbar1">
<ul class="nav navbar-nav navbar-right">
<li><a href="login.php">Login</a></li>
<li class="active"><a href="register.php">Sign Up</a></li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4 well">
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="signupform">
<fieldset>
<legend>Sign Up</legend>
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Enter Full Name" required value="<?php if($error) echo $name; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($name_error)) echo $name_error; ?></span>
</div>
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" placeholder="Email" required value="<?php if($error) echo $email; ?>" class="form-control" />
<span class="text-danger"><?php if (isset($email_error)) echo $email_error; ?></span>
</div>
<div class="form-group">
<label for="name">Password</label>
<input type="password" name="password" placeholder="Password" required class="form-control" />
<span class="text-danger"><?php if (isset($password_error)) echo $password_error; ?></span>
</div>
<div class="form-group">
<label for="name">Confirm Password</label>
<input type="password" name="cpassword" placeholder="Confirm Password" required class="form-control" />
<span class="text-danger"><?php if (isset($cpassword_error)) echo $cpassword_error; ?></span>
</div>
<div class="form-group">
<input type="submit" name="signup" value="Sign Up" class="btn btn-primary" />
</div>
</fieldset>
</form>
<span class="text-success"><?php if (isset($successmsg)) { echo $successmsg; } ?></span>
<span class="text-danger"><?php if (isset($errormsg)) { echo $errormsg; } ?></span>
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-4 text-center">
Already Registered? <a href="login.php">Login Here</a>
</div>
</div>
</div>
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
Read: How to Use Google reCAPTCHA in PHP Form
This is how the registration form looks like.
Registration form requires user to fill up name, email id and password and confirm password fields. All the fields are mandatory and user will be asked to provide the data if it is left blank like this.
Once the user fills out the details and submits the form for sign up, we sanitize the received data to avoid sql injection and validate the form input. If validation fails the user will be shown with the appropriate error message below each form input like this.
If the validation succeeds the data will be stored in the database and user will be shown with the login link.
Login.php
This file contains the php code for user login process. The access to login form will be restricted for signed in users by checking if the php session is set or not.
<?php
session_start();
if(isset($_SESSION['usr_id'])!="") {
header("Location: index.php");
}
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
header("Location: index.php");
} else {
$errormsg = "Incorrect Email or Password!!!";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Login Script</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport" >
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<!-- add header -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php">Koding Made Simple</a>
</div>
<!-- menu items -->
<div class="collapse navbar-collapse" id="navbar1">
<ul class="nav navbar-nav navbar-right">
<li class="active"><a href="login.php">Login</a></li>
<li><a href="register.php">Sign Up</a></li>
</ul>
</div>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4 well">
<form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="loginform">
<fieldset>
<legend>Login</legend>
<div class="form-group">
<label for="name">Email</label>
<input type="text" name="email" placeholder="Your Email" required class="form-control" />
</div>
<div class="form-group">
<label for="name">Password</label>
<input type="password" name="password" placeholder="Your Password" required class="form-control" />
</div>
<div class="form-group">
<input type="submit" name="login" value="Login" class="btn btn-primary" />
</div>
</fieldset>
</form>
<span class="text-danger"><?php if (isset($errormsg)) { echo $errormsg; } ?></span>
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-4 text-center">
New User? <a href="register.php">Sign Up Here</a>
</div>
</div>
</div>
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
This file produces a login form similar to this.
Login form requires users to provide login credentials (email & password). Both the input fields are mandatory and notify user to fill out if left blank.
Here too we sanitize the data and check for user authentication against database records. If it fails, we notify the user with error message like this,
If the user credentials are legitimate then we create session and store user's id and name in the session variable and redirect to index.php.
Read: How to Upload & Watermark Images with PHP
Index.php
This is the home page of our application and shows login and sign up menu links for visitors and for signed in members will show their name and logout link respectively.
<?php
session_start();
include_once 'dbconnect.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Home | Koding Made Simple</title>
<meta content="width=device-width, initial-scale=1.0" name="viewport" >
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php">Koding Made Simple</a>
</div>
<div class="collapse navbar-collapse" id="navbar1">
<ul class="nav navbar-nav navbar-right">
<?php if (isset($_SESSION['usr_id'])) { ?>
<li><p class="navbar-text">Signed in as <?php echo $_SESSION['usr_name']; ?></p></li>
<li><a href="logout.php">Log Out</a></li>
<?php } else { ?>
<li><a href="login.php">Login</a></li>
<li><a href="register.php">Sign Up</a></li>
<?php } ?>
</ul>
</div>
</div>
</nav>
<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
Logout.php
This file will be fired up when the user clicks on the logout link. The user logout process is fairly simple. It destroy session and unset the user data from the session.
<?php
session_start();
if(isset($_SESSION['usr_id'])) {
session_destroy();
unset($_SESSION['usr_id']);
unset($_SESSION['usr_name']);
header("Location: index.php");
} else {
header("Location: index.php");
}
?>
Once you created all the above files, run the app and you will see the home page like this,
index.php - Home Page |
Now click on the sign up link and you will be redirected to the user registration form,
Now enter the form details and submit the sign up button. If everything goes right then you will be registered and notified with a message like this,
Now go to the login form through the login link.
Provide the login credentials and you will be signed in and redirected to the index page.
index.php as signed-in user |
Click on logout to sign out the session and you will be taken back to the index page again.
After Log out |
That's it. You have successfully created user login and registration system in php and mysql.
Read Also:- AJAX Modal Login Page using PHP OOP, MySQL and jQuery
- CRUD [Create, Read, Update, Delete] in PHP, MySQL & jQuery
- Dynamic Image Gallery from Folder in PHP, JQuery & Bootstrap
I hope you find this php login/registration script useful. Meet you in another interesting tutorial!
Last Modified: 27-Nov-2017