In this tutorial we are going to explain How to create advanced Registration and Login Script in PHP with MySQLi. This is basic requirement of every web application, allow user to register on website and access secure area for logged in users. We have created this script in procedural way, so its easy to implement with your web application.
In this script we also used form input validation like password length, email validation, input field validation etc.. In this script we are using PHP 7 version.
Steps to Create Registration and Login Script in PHP and MySQLi
1) Create Database table with Five column : id, username, email, password, register_date
2) Create Database Connection using PHP MySQLi
3) Make Registration form
4) Create Form Input Field jQuery Validation
5) Write MySQLi Prepared Statements to insert user data
6) Make Login Form
7) Authenticate User
8) Create Index Page
9) Create Logout Page
Lets start to learn by following above mentioned steps:
1) Create Database table
First create an database table using below MySQL query. This will create 5 column database table, make ‘id’ column as primary key.
1 2 3 4 5 6 7 |
CREATE TABLE `register_users` ( `id` int(11) NOT NULL, `username` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `register_date` datetime NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; |
2) Create Database Connection using PHP MySQLi
Now write down an PHP script to make database connection using MySQLi. Create a database.php file and mention your database configuration access. Use below code to create database connection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php /* database configuration */ $servername = 'localhost'; $username = 'USERNAME'; $password = 'PASSWORD'; $db = 'DATABASE NAME'; $conn = mysqli_connect($servername,$username,$password,$db) ; if (!$conn) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } ?> |
3) Make Registration form
Create an register.php page and make an HTML form to take user input like Username, Email, Password. We are using Bootstrap HTML form, just include the bootstrap CSS and JS link in it. You don’t need to build your own CSS. Check below code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<!DOCTYPE html> <html lang="en"> <head> <title>User Registeration Form</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div style="margin-top:5%" class="container"> <div class="col-sm-4"> </div> <div class="row"> <div class="col-sm-4" style="background:#eeeeee;"> <h2>Register form</h2> <form id="formID" action="" method="POST"> <div class="form-group"> <label>Username:</label> <input type="text" class="form-control" id="username" placeholder="Enter Username" name="username"> </div> <div class="form-group"> <label>Email:</label> <input type="email" name="email" placeholder="Enter Email" id="email" class="form-control"> </div> <div class="form-group"> <label>Password:</label> <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd"> </div> <div class="form-group"> <label>Confirm Password:</label> <input type="password" class="form-control" id="cnfpwd" placeholder="Confirm password" name="confirmpwd"> </div> <div class="form-group"> <input type="submit" name="register" id="register" value="Register" class="btn btn-default" style="margin-left: 40%;"/> </div> </form> <p>Click here to <a href='login.php'>Login</a></p> </div> </div> </div> </body> </html> |
4) Create Form Input Field jQuery Validation
We have putted many validation in this registration form. Like check input fields are empty or not, check for valid email and Password strength.
To check valid email we are using PHP sanitize and validate method. After submit the form, Remove all illegal characters from it and checking email is valid or not like:
1 2 3 4 5 6 7 8 9 10 |
// Remove all illegal characters from email $email = filter_var($submitemail, FILTER_SANITIZE_EMAIL); // Validate e-mail address if(filter_var($submitemail, FILTER_VALIDATE_EMAIL)) { echo 'email is valid'; } |
For other validation we are using jQuery, check it below script code which perform all validation. Place this script code in register.php page in Head section.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<script> $(document).ready(function() { $("#register").click(function() { var name = $("#username").val(); var email = $("#email").val(); var password = $("#pwd").val(); var cpassword = $("#cnfpwd").val(); if (name == '' || email == '' || password == '' || cpassword == '') { alert("Please fill all fields...!!!!!!"); $('#formID').attr('onSubmit','return false'); } else if ((password.length) < 8) { alert("Password should atleast 8 character in length...!!!!!!"); $('#formID').attr('onSubmit','return false'); } else if (!(password).match(cpassword)) { alert("Your passwords don't match. Try again?"); $('#formID').attr('onSubmit','return false'); } else { $('#formID').attr('onSubmit','return true'); } }); }); </script> |
In this script validate fields on form submit. To stop form submit after alert message return false value on form submit via its attribute. Like:
$(‘#formID’).attr(‘onSubmit’,’return false’);
5) Write MySQLi Prepared Statements to insert user data
Now write down MySQLi queries to insert register form data in database table. We are using MySQLi Prepared Statements to insert data. Prepared statements are very useful against SQL injections. Using this way you can apply same SQL injection repeatedly with high frequency.
In this process, first we write down the insert query like this:
$stmt = $conn->prepare(“INSERT INTO register_users (username, email, password, register_date) VALUES (?, ?, ?, ?)”);
Than bind the input parameter with this SQL injection command.
$stmt->bind_param(“ssss”, $username, $email, $password, $register_date);
In this ‘ssss’ describe the input data is string. First ‘s’ describe that username is string value. For integer value we use ‘i’ value.
Now to execute this MySQLi query use below command:
$stmt->execute();
$stmt->close();
To insert registration form data in database, use below PHP code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<?php if (isset($_POST['username'])) { $statement = $conn->prepare("Select * from register_users where username = ? OR email = ?"); $statement->bind_param("ss", $username, $email); $stmt = $conn->prepare("INSERT INTO register_users (username, email, password, register_date) VALUES (?, ?, ?, ?)"); $stmt->bind_param("ssss", $username, $email, $password, $register_date); // set parameters and execute $username = $_POST['username']; $submitemail = $_POST['email']; // Remove all illegal characters from email $email = filter_var($submitemail, FILTER_SANITIZE_EMAIL); $password = md5($_POST['pwd']); $register_date = date("Y-m-d H:i:s"); // execute Select query $statement->execute(); $statement->store_result(); $numrows = $statement->num_rows; $statement->close(); // Validate e-mail address if(filter_var($submitemail, FILTER_VALIDATE_EMAIL)) { if($numrows == 0) { $stmt->execute(); $stmt->close(); } else { $checkuser = "Username Or Email Already Used"; } } else { $validate_msg = "$submitemail is Not valid email address"; } if($conn->insert_id) { $msg = "<h3>Registered successfully.</h3>"; } else { $msg = "Registration Failed"; } } ?> |
To view error message, we are using $msg, $checkuser and $validate_msg variables. To display these message just put in HTML form via PHP tag. Like :
1 |
<?php echo $validate_msg; echo $checkuser; echo "<br/>"; echo $msg; ?> |
6) Make Login Form
Now create an login.php page for Login form. Use below code to execute login process:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
<!DOCTYPE html> <html lang="en"> <head> <title>Login Form</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <?php if (isset($_POST['username'])){ $username = $_POST['username']; $password = md5($_POST['pwd']); $stmt = $conn->prepare("SELECT username, password FROM register_users where username='$username' and password = '$password'"); /* execute statement */ $stmt->execute(); /* bind result variables */ $stmt->bind_result($user, $pass); /* fetch values */ while ($stmt->fetch()) { } if($user == $username) { session_start(); $_SESSION['name'] = $user; // Redirect user to index.php header("Location: index.php"); } else { $msg = "Your username or password is wrong"; } $stmt->close(); } ?> <body> <div style="margin-top:5%" class="container"> <div class="col-sm-4"> </div> <div class="row"> <div class="col-sm-4" style="background:#eeeeee;"> <?php echo $msg; ?> <h2>Login form</h2> <form action="" method="POST"> <div class="form-group"> <label>Username:</label> <input type="text" class="form-control" id="username" placeholder="Enter Username" name="username"> </div> <div class="form-group"> <label>Password:</label> <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd"> </div> <div class="form-group"> <button style="margin-left: 40%;" type="submit" class="btn btn-default">Login</button> </div> </form> <p>Click here to <a href='register.php'>Register</a></p> </div> </div> </div> </body> </html> |
7) Authenticate User
Create a session.php page to check the user session. Include this PHP file on require page to check user has access to view it or not.
In this we are checking “$_SESSION[‘name’]” is empty or not. If session is empty than redirect the user to Login page.
1 2 3 4 5 6 7 8 9 10 11 |
<?php session_start(); if(!isset($_SESSION['name'])) { header("Location: login.php"); exit(); } ?> |
8) Create Index Page
Now create an index.php as secure page. After successful login user can view this page. Check below code to create this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php require("session.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <title>Home Page</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div style="margin-top:5%" class="container"> <div align="center" class="row"> <div class="col-sm-12" style="background:#eeeeee;"> <p>Welcome <?php echo $_SESSION['name']; ?>!</p> <p>This is secure area.</p> <a href="logout.php">Logout</a> </div> </div> </div> </body> </html> |
9) Create Logout Page
Create a logout.php file to destroy the user session. It will remove the current user session and redirect back to login page. We have placed this logout page link in Index page.
1 2 3 4 5 6 7 8 9 10 11 |
<?php session_start(); // Destroying All Sessions if(session_destroy()) { // Redirecting To Home Page header("Location: login.php"); } ?> |
All done. Using above mentioned steps you can easily create registration and login Script in PHP and MySQLi with Validation. We hope this tutorial help you to create this functionality. If you found it useful please share it and leave your feedback.
Check Live demo and Free Download source code also available.
DEMO | Download Social Login Script
Fantastic Soft Hat