According to Wikipedia, Registration is a method of officially recording something. Usually, something is registered to claim more rights, or to protect ownership, or because the law says it must be registered to be used legally. In this tutorial, I put you through the complete process of creating a user registration and login system where users can create an account by providing full name, username, email, and password, log in and log out using PHP, MySQL, and Javascript validation. Note: The time a user registered and a default profile picture will also be included.

The first thing we'll need to do is set up our database. 
Create a database called registration. In the user-registration database, add a table called user. The user table will take the following six fields.

id
fullname  -  varchar(250) 
username  -  varchar(250)
email  -  varchar(250)
password  -  varchar(250)
profile_pic  -  varchar(250)
created_at  -  type(TIMESTAMP) default(CURRENT_TIMESTAMP) attributes(on update CURRENT_TIMESTAMP)

You can create this using a MySQL client like PHPMyAdmin.

Or you can create it on the MySQL prompt using the following SQL script:

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fullname` varchar(250) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(200) NOT NULL,
  `email` varchar(255) NOT NULL,
  `profile_pic` varchar(250) NOT NULL,
  `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=latin1;
COMMIT;

And that's it with the database. 

Now create a folder called registration in a directory accessible to our server. i.e create the folder inside htdocs (if you are using XAMPP server) or inside www (if you are using wampp server).

Inside the folder registration, create the following files: 

Open these files up in a text editor of your choice.

Registering a user

Open the register.php file and paste the following code into it:
user-registration.php:

<?php include("includes/controller.php"); ?>

<HTML>
<HEAD>
<TITLE>User Registration Page</TITLE>
<link href="assets/css/style.css?version1" type="text/css"
	rel="stylesheet" />
<link href="assets/css/main.css?version2" type="text/css"
	rel="stylesheet" />
<script src="assets/jquery/jquery-3.3.1.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</HEAD>
<BODY>
	<div class="g7conet-container">
		<div class="sign-up-container">
			<div class="login-signu">
				<a href="#">Back Home</a>
			</div>
			<div class="login-signup">
				<a href="index.php">Login</a>
			</div>
			<div class="">
				<form name="sign-up" action="" method="post"
					onsubmit="return signupValidation()">
					<div class="signup-heading">Registration</div>
					
			<?php if (count($errors) > 0): ?>
            <center>
            <div class="alert alert-danger" style="">
            <?php foreach ($errors as $errors): ?>
            <p style="text-align: center"><?php echo $errors; ?></p>
            <?php endforeach; ?>
            </div>
            </center>
        	<?php endif; ?> 


				<div class="error-msg" id="error-msg"></div>
					<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Fullname<span class="required error" id="fullname-info"></span>
							</div>
							<input class="input-box-330" type="text" name="fullname"
								id="fullname">
						</div>
					</div>
					<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Username<span class="required error" id="username-info"></span>
							</div>
							<input class="input-box-330" type="text" name="username"
								id="username">
						</div>
					</div>
					<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Email<span class="required error" id="email-info"></span>
							</div>
							<input class="input-box-330" type="email" name="email" id="email">
						</div>
					</div>
					<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Password<span class="required error" id="signup-password-info"></span>
							</div>
							<input class="input-box-330" type="password"
								name="password" id="signup-password">
						</div>
					</div>
					<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Confirm Password<span class="required error"
									id="confirm-password-info"></span>
							</div>
							<input class="input-box-330" type="password"
								name="passwordcof" id="confirm-password">
						</div>
					</div>
					<div class="row">
						<div class="inline-block">
							<input class="input-box-330" type="checkbox"
								required> Yes, I have read and consent to the
  								<a style="color: #d96438;" href="#">Terms & Conditions
						</div>
					</div>

					<div class="row">
						<input class="btn" type="submit" name="join"
							id="signup-btn" value="Sign up">
					</div>
				</form>
			</div>
		</div>
	</div>

	<script>
function signupValidation() {
	var valid = true;

	$("#fullname").removeClass("error-field");
	$("#username").removeClass("error-field");
	$("#email").removeClass("error-field");
	$("#password").removeClass("error-field");
	$("#confirm-password").removeClass("error-field");

	var fullName = $("#fullname").val();
	var UserName = $("#username").val();
	var email = $("#email").val();
	var Password = $('#signup-password').val();
    var ConfirmPassword = $('#confirm-password').val();
	var emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;

	$("#fullname-info").html("").hide();
	$("#username-info").html("").hide();
	$("#email-info").html("").hide();

	if (fullName.trim() == "") {
		$("#fullname-info").html("required.").css("color", "#d96438").show();
		$("#fullname").addClass("error-field");
		valid = false;
	}
	if (UserName.trim() == "") {
		$("#username-info").html("required.").css("color", "#d96438").show();
		$("#username").addClass("error-field");
		valid = false;
	}
	if (email == "") {
		$("#email-info").html("required").css("color", "#d96438").show();
		$("#email").addClass("error-field");
		valid = false;
	} else if (email.trim() == "") {
		$("#email-info").html("Invalid email address.").css("color", "#d96438").show();
		$("#email").addClass("error-field");
		valid = false;
	} else if (!emailRegex.test(email)) {
		$("#email-info").html("Invalid email address.").css("color", "#d96438")
				.show();
		$("#email").addClass("error-field");
		valid = false;
	}
	if (Password.trim() == "") {
		$("#signup-password-info").html("required.").css("color", "#d96438").show();
		$("#signup-password").addClass("error-field");
		valid = false;
	}
	if (ConfirmPassword.trim() == "") {
		$("#confirm-password-info").html("required.").css("color", "#d96438").show();
		$("#confirm-password").addClass("error-field");
		valid = false;
	}
	if(Password != ConfirmPassword){
        $("#error-msg").html("Both passwords must be same.").show();
        valid=false;
    }
	if (valid == false) {
		$('.error-field').first().focus();
		valid = false;
	}
	return valid;
}
</script>
</BODY>
</HTML>

Note: On the first line of our user-registration.php file, we are including a file that contains our PHP script responsible for receiving the form values and processing them.
We are also validating our form with javascript. Please do well to get a jquery file and save it in the jquery folder. All the data is received from the form and checked to make sure that the user correctly filled the form. Passwords are also compared to make sure they match.

As you can see in the head section, we are linking to a style.css file. Open up the style.css file and paste the following CSS in it:
style.css:

/* version 3.0 table added */
.g7conet-container {
	-webkit-font-smoothing: antialiased;
	font-family: Arial, "Helvetica Neue", Helvetica, sans-serif;
	font-size: .9em;
	color: #1e2a28;
	width: 740px;
	margin: 0 auto;
	padding: 0px 20px 20px 20px;
}

.g7conet-container table {
	border-collapse: collapse;
	width: 100%;
	margin-bottom: 30px;
}

.g7conet-container td, .g7conet-container th {
	text-align: left;
	padding: 8px;
}

.g7conet-container h1 {
	font-weight: normal;
}

input[type=text].g7conet-input, .g7conet-container input,
	.g7conet-container textarea, .g7conet-container select, .g7conet-input,
	.g7conet-select {
	box-sizing: border-box;
	width: 200px;
	height: initial;
	padding: 8px 5px;
	border: 1px solid #9a9a9a;
	border-radius: 3px;
}

.g7conet-container input[type="checkbox"] {
	width: auto;
	vertical-align: text-bottom;
	display: initial;
	opacity: initial;
	position: inherit;
	pointer-events: initial;
}

.g7conet-container textarea, .g7conet-textarea {
	width: 300px;
}

.g7conet-container select, .g7conet-select {
	display: initial;
	height: 30px;
	background-color: #fff;
	padding: 2px 5px;
}

.g7conet-container button, .g7conet-container input[type=submit] {
	padding: 8px 0px;
	font-size: 1em;
	cursor: pointer;
	border-radius: 3px;
	color: white;
	font-weight: bold;
	background-color: #d96438;
	border-color: #d96438;
}

.g7conet-container button, .g7conet-container input[type=submit]:hover {
	background-color: white;
	color: #d96438;
	border-color: #d96438;
}

.g7conet-container button:focus {
	outline: none;
}

.g7conet-container .g7conet-row {
	padding-top: 15px;
}

#g7conet-message {
	padding: 6px 20px;
	font-size: 1em;
	color: rgb(40, 40, 40);
	box-sizing: border-box;
	margin: 0px;
	border-radius: 3px;
	width: 100%;
	overflow: auto;
}

.g7conet-container .error {
	padding: 6px 20px;
	border-radius: 3px;
	background-color: #fb817c;
	border: 1px solid #e46b66;
}

.g7conet-container .success {
	background-color: #48e0a4;
	border: #40cc94 1px solid;
}

#g7conet-loader-icon {
	color: #1871e6;
	font-weight: bold;
	padding: 6px 20px 6px 0;
	display: none;
	vertical-align: middle;
}

#g7conet-loader-ack-icon {
	color: #1871e6;
	font-weight: bold;
	padding: 6px 20px 6px 0;
	display: none;
	vertical-align: middle;
}

#g7conet-btn-send:hover {
	background: #1363cc;
	border: #105bbd 1px solid;
}

.g7conet-container .validation-message {
	color: #e20900;
	display: inline-block;
}

.g7conet-container .label {
	margin-bottom: 3px;
}

.g7conet-form, .g7conet-section {
	border: #eaeaea 1px solid;
	padding: 10px 25px 10px 30px;
	border-radius: 3px;
}

.g7conet-container .display-none {
	display: none;
}

.icon-add-more-attachemnt {
	cursor: pointer;
	font-style: italic;
	font-size: .9em;
}

.inline-block {
	display: inline-block;
}

@media all and (max-width: 780px) {
	.g7conet-container {
		width: auto;
	}
}

@media all and (max-width: 400px) {
	.g7conet-container {
		padding: 0px 20px;
	}
	.g7conet-container h1 {
		font-size: 1.2em;
	}
	.g7conet-container input, .g7conet-container textarea, .g7conet-container select
		{
		width: 100%;
	}
	.g7conet-form {
		border: none;
		padding: 0;
	}
}

Do the same with the main.css file. They are both for styling
main.css:

.sign-up-container {
	border: 1px solid;
	border-color: #9a9a9a;
	background: #fff;
	border-radius: 4px;
	padding: 10px;
	width: 350px;
	margin: 50px auto;
}

.page-header {
	float: right;
}

.login-sign {
	margin: 5px;
	text-decoration: none;
	float: center;
}

.login-sign a {
	text-decoration: none;
	font-weight: 750;
	color: #d96438;
}

.login-sign a:hover{
	color: black;
}

.login-signu {
	margin: 5px;
	text-decoration: none;
	float: left;
}

.login-signu a {
	text-decoration: none;
	font-weight: 750;
	color: #d96438;
}

.login-signu a:hover{
	color: black;
}

.login-signup {
	margin: 5px;
	text-decoration: none;
	float: right;
}

.login-signup a {
	text-decoration: none;
	font-weight: 750;
	color: #d96438;
}

.login-signup a:hover{
	color: black;
}

.signup-heading {
	font-size: 2em;
	font-weight: bold;
	padding-top: 60px;
	text-align: center;
}

.inline-block {
	display: inline-block;
}

.row {
	margin: 15px 0px;
	text-align: center;
}

.form-label {
	margin-bottom: 5px;
	text-align: left;
}

input.input-box-330 {
	width: 250px;
}

.sign-up-container .error {
	color: #d96438;
	padding: 0px;
	background: none;
	border: #d96438;
}

.sign-up-container .error-field {
	border: 1px solid #d96557;
}

.sign-up-container .error:before {
	content: '*';
	padding: 0 3px;
	color: #D8000C;
}

.error-msg {
	padding-top: 10px;
	color: #D8000C;
	text-align: center;
}

.success-msg {
    padding-top: 10px;
	color: #176701;
	text-align: center;
}

input.btn {
	width: 250px
}

.signup-align {
	margin: 0 auto;
}

.page-content {
	font-weight: bold;
	padding-top: 60px;
	text-align: center;
	font-size: 50px;
}

img{
	width: 150px;
	height: 150px;
	float: left;

Now, in the index.php file created already copy and paste the below code there. This file contains the login code with javascript validation code. 
index.php:

<?php include("includes/controller.php"); ?>

<HTML>
<HEAD>
<TITLE>User Login Page</TITLE>
<link href="assets/css/style.css?version1" type="text/css"
	rel="stylesheet" />
<link href="assets/css/main.css?version2" type="text/css"
	rel="stylesheet" />
<script src="assets/jquery/jquery-3.3.1.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</HEAD>
<BODY>
	<div class="g7conet-container">
		<div class="sign-up-container">
			<div class="login-signu">
				<a href="#">Back Home</a>
			</div>
			<div class="login-signup">
				<a href="user-registration.php">Sign up</a>
			</div>
			<div class="signup-align">
				<form name="login" action="" method="post"
					onsubmit="return loginValidation()">
					<div class="signup-heading">Login</div>
				
			<?php
            
            if(isset($_SESSION['login_fail'])){
                ?>
                <div style="text-align: center; padding: 5px;" class="alert alert-danger">
                    <?php echo $_SESSION['login_fail']; ?>
                </div>
                <?php

                unset($_SESSION['login_fail']);
            }
            ?>      

				<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Username<span class="required error" id="username-info"></span>
							</div>
							<input class="input-box-330" type="text" name="username"
								id="username" placeholder="Enter email or username">
						</div>
					</div>
					<div class="row">
						<div class="inline-block">
							<div class="form-label">
								Password<span class="required error" id="login-password-info"></span>
							</div>
							<input class="input-box-330" type="password"
								name="password" id="login-password" placeholder="Enter password">
						</div>
					</div>
					<div class="row">
						<input class="btn" type="submit" name="login"
							id="login-btn" value="Login">
					</div>
					
				</form>
			</div>
		</div>
	</div>

	<script>
function loginValidation() {
	var valid = true;
	$("#username").removeClass("error-field");
	$("#password").removeClass("error-field");

	var UserName = $("#username").val();
	var Password = $('#login-password').val();

	$("#username-info").html("").hide();

	if (UserName.trim() == "") {
		$("#username-info").html("required.").css("color", "#d96438").show();
		$("#username").addClass("error-field");
		valid = false;
	}
	if (Password.trim() == "") {
		$("#login-password-info").html("required.").css("color", "#d96438").show();
		$("#login-password").addClass("error-field");
		valid = false;
	}
	if (valid == false) {
		$('.error-field').first().focus();
		valid = false;
	}
	return valid;
}
</script>
</BODY>
</HTML>

We will create a simple home page where all the login and registered users redirect to. In the home.php, copy the below code and paste it there.
home.php:

<?php
include("includes/controller.php");
if (!isset($_SESSION['username'])){
    header('location: user-login.php');
    exit();
  }
?>
<HTML>
<HEAD>
<TITLE>Welcome Page</TITLE>
<link href="assets/css/style.css?version3" type="text/css"
	rel="stylesheet" />
<link href="assets/css/main.css?version4" type="text/css"
	rel="stylesheet" />
</HEAD>
<BODY>
	<div class="phppot-container">
		<div class="page-header">

			<span class="login-signup"><a href="logout.php">Logout</a></span>
		</div>
		<div class="image">
				<img src="<?php echo $_SESSION['profile_pic']; ?>">
			</div>

			<?php 
                if(isset($_SESSION['success'])){
                    ?>
                    <div style="text-align: center; padding: 5px;" class="success">
                        <?php echo $_SESSION['success']; ?>
                    </div>
                    <?php

                    unset($_SESSION['success']);
                }
            ?>      
		<div class="page-content">Welcome <?php echo $username;?></div>
	</div>
	
</BODY>
</HTML>

Logout page
Once a user registers or login he is redirected to the home and there will be a logout button to log the user out of the account. 
logout.php:

<?php
// clear all the session variables and redirect to index
session_start();
session_unset();
session_write_close();
$url = "./index.php";
header("Location: $url");

Inside the root folder, there is another called includes which house the db.php and controller.php files.
Open the db.php copy the below code and paste it there.
db.php:

<?php
$con=mysqli_connect("localhost","root","","user-registration");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  
 ?>

The code above is the database connection that connects the controller file to the database.
Now, open the controller.php and paste the below code there.
controller.php:

<?php 
session_start();

include("db.php"); 

//User registration
// initializing variables
$fullname = "";
$username = "";
$email    = "";
$errors =array();


// REGISTER USER
if (isset($_POST['join'])) {
  // receive all input values from the form
  $fullname = mysqli_real_escape_string($con, $_POST['fullname']);
  $username = mysqli_real_escape_string($con, $_POST['username']);
  $email = mysqli_real_escape_string($con, $_POST['email']);
  $password = mysqli_real_escape_string($con, $_POST['password']);
  $passwordcof = mysqli_real_escape_string($con, $_POST['passwordcof']);

  // form validation: ensure that the form is correctly filled ...
  // by adding (array_push()) corresponding error unto $errors array
  
  if (strlen($password) <=7){ array_push($errors, "Your password must be more than 8 characters"); }
  

  // first check the database to make sure 
  // a user does not already exist with the same username and/or email
  $user_check_query = "SELECT * FROM user WHERE username='$username' OR email='$email' LIMIT 1";
  $result = mysqli_query($con, $user_check_query);
  $user = mysqli_fetch_assoc($result);
  
  if ($user) { // if user exists
    if ($user['username'] === $username) {
      array_push($errors, "Username already exists");
    }

    if ($user['email'] === $email) {
      array_push($errors, "Email already exists");
    }
  }

  $profile_pic = "profile.jpg"; 

  // Finally, register user if there are no errorss in the form
  if (count($errors) == 0) {
    $password = password_hash($password, PASSWORD_DEFAULT);//encrypt the password before saving in the database
   

    $query = "INSERT INTO user (fullname, username, email, password, profile_pic) 
          VALUES('$fullname', '$username', '$email', '$password', '$profile_pic')";
    mysqli_query($con, $query);
    $_SESSION['username'] = $username;
    $_SESSION['fullname'] = $fullname;
    $_SESSION['email'] = $email;
    $_SESSION['created_at'] = $created_at;
    $_SESSION['profile_pic'] = $profile_pic;
    $_SESSION['success'] = "You have registered successfully";
    header('location: home.php');
    exit();
  }
}

//if user clicks on the login button
if (isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];


if (count($errors) ===0){

$sql = "SELECT * FROM user WHERE email=? OR username=? LIMIT 1";
$stmt = $con->prepare($sql);
$stmt->bind_param('ss', $username, $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if(password_verify($password, $user['password'])){

  //login success
    $user_id = $con->insert_id;
    $_SESSION['id'] = $user['id'];
    $_SESSION['fullname'] = $user['fullname'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['email'] = $user['email'];
    $_SESSION['created_at'] = $user['created_at'];
    $_SESSION['profile_pic'] = $user['profile_pic'];
   // set flash message
    $_SESSION['succes'] = "You are now logged in, welcome back!";
    header('location: home.php');
    exit(); 
}
else
{
  $_SESSION['login_fail'] = "Wrong Credentials";
}

}

}

Sessions are used to track logged-in users and so we include a session_start() at the top of the file. 
The if statements determine if the registration/login button on the registration/login form is clicked. Remember, in our registration/login forms, the submit button has a name(s) attribute set to join/login respectively and that is what we are referencing in the if statement.

If no errors were encountered, the user is registered in the user's table in the database with a hashed password. The hashed password is for security reasons. It ensures that even if a hacker manages to gain access to your database, they would not be able to read your password.

Note: You can download the full source code and do the installation yourself.

Requirements

  1. Download and Install any local web server such as XAMPP/WAMP.
  2. Download the provided source code zip file. (download button is located below)

Installation/Setup

  1. Open your XAMPP/WAMP's Control Panel and start Apache and MySQL.
  2. Extract the downloaded source code zip file.
  3. If you are using XAMPP, copy the image_preview folder from the extracted source code folder and paste it into the XAMPP's "htdocs" directory. And If you are using WAMP, paste it into the "www" directory.
  4. Open your XAMPP/WAMP PHPMyAdmin in a browser and create a new database naming user-registration.
  5. Import the provided SQL file into your newly created database. The file is located inside the database folder and is known as user.sql.
  6. Browse the Image Preview System in a browser. i.e. http://localhost/user-registration.

Now go on, customize it to suit your needs, and build an awesome site. If you have any worries or anything you need to clarify, leave it in the comments below and help will come.

You can always support by sharing on social media or recommending our website to your friends and colleagues.