Skip to main content

User Registration and Login System with PHP & MySQL

User registration and login is an important feature of web applications to allow user to manage their account. The user registration is allowed to visitors to maintain their profiles and access to certain sections.

So if you’re looking for implementing user registration and login system then you’re here at the right place. In our previous tutorial you have learned how to Filter Search Result with Ajax, PHP & MySQL. In this tutorial, you will learn how to implement user registration and login using PHP and MySQL.

We will gone through step by step to create live example of user login and registration script with PHP and MySQL.

Also, read:

So let’s implement user login and registration script with PHP & MySQL. The major files are:

  • Index.php
  • login.php
  • register.php
  • logout.php
  • User.php: A class that hold methods related to user login and register.

Step1: Create MySQL Database Table

As we will implement user registration and login script, so we will create MySQL database table users to store registered user details.

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `fname` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `lname` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `phone` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  `modified` datetime NOT NULL,
  `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Step2: Implement User Register Functionality

In register.php file, we will design user registration form.

<div id="login-row" class="row justify-content-center align-items-center">
	<div id="login-column" class="col-md-6">
		<div id="login-box" class="col-md-12">
			<form id="login-form" class="form" action="" method="post">
				<h3 class="text-center text-info">User Registration</h3>							
				<?php if($message) { ?>
				<br>
				<div class="form-group">
					<span class="alert alert-danger"><?php echo $message; ?></span>
				</div>
				<br>
				<?php } ?>							
				<div class="form-group">
					<label for="fname" class="text-info">First Name*:</label><br>
					<input type="text" name="fname" id="fname" class="form-control" required>
				</div>
				<div class="form-group">
					<label for="lname" class="text-info">Last Name:</label><br>
					<input type="text" name="lname" id="lname" class="form-control">
				</div>
				<div class="form-group">
					<label for="email" class="text-info">Email*:</label><br>
					<input type="email" name="email" id="email" class="form-control" required>
				</div>
				<div class="form-group">
					<label for="phone" class="text-info">Phone Number:</label><br>
					<input type="number" name="phone" id="phone" class="form-control">
				</div>
				<div class="form-group">
					<label for="password" class="text-info">Password*:</label><br>
					<input type="password" name="password" id="password" class="form-control" required>
				</div>
				<div class="form-group">
					<label for="cpassword" class="text-info">Confirm Password*:</label><br>
					<input type="password" name="cpassword" id="cpassword" class="form-control" required>
				</div>
				<div class="form-group">	
					<input type="submit" name="register" class="btn btn-info btn-md" value="Register">
					Have already account? <a href="login.php" class="text-info">Login</a> here.
				</div>	
			</form>
		</div>
	</div>
</div>

We will implement user register functionality by calling register() method from class User.php.

$user = new User();
$message = '';
if(isset($_POST['register'])){
	$message = $user->register();	
}

In class User.php, we will implement register() method to handle user registration.

public function register(){		
	$message = '';
	if(!empty($_POST['fname']) && !empty($_POST['lname']) 
	&& !empty($_POST['email']) && !empty($_POST['phone']) 
	&& !empty($_POST['password']) && !empty($_POST['cpassword'])){		
		if($_POST['password'] !== $_POST['cpassword']){
			$message = 'Confirm password must match with the password.'; 
		}else {
			$sqlQuery = "
				SELECT * 
				FROM ".$this->usersTable." 
				WHERE email='".$_POST['email']."'";
			$result = mysqli_query($this->dbConnect, $sqlQuery);
			$userEmailExist = mysqli_num_rows($result);
			if($userEmailExist){					
				$message = 'Email already exists, please use another email.';
			}else{
				$insertUser = "
					INSERT INTO ".$this->usersTable." (fname, lname, email, phone, password) 
					VALUES ('".$_POST['fname']."', '".$_POST['lname']."', '".$_POST['email']."', '".$_POST['phone']."', '".md5($_POST['password'])."')";
				$userInserted = mysqli_query($this->dbConnect, $insertUser);					
				if($userInserted){						
					$message = 'You have registered successfully, <a href="login.php">log in</a> with your credentials.';
				}else{						
					$message = 'Some problem occurred, please try again.';
				}
			}
		}			
	} else {			
		$message = 'All fields are mandatory, please fill all the fields.'; 
	}	
	return $message;
}

Step3: Implement User Login Functionality

In login.php file, we will design user login form to perform user login functionality.

<div id="login-row" class="row justify-content-center align-items-center">
	<div id="login-column" class="col-md-6">
		<div id="login-box" class="col-md-12">
			<form id="login-form" class="form" action="" method="post">
				<h3 class="text-center text-info">User Login</h3>							
				<?php if($message) { ?>
				<br>
				<div class="form-group">
					<span class="alert alert-danger"><?php echo $message; ?></span>
				</div>
				<br>
				<?php } ?>							
				<div class="form-group">
					<label for="email" class="text-info">Email:</label><br>
					<input type="text" name="email" id="email" class="form-control">
				</div>							
				<div class="form-group">
					<label for="password" class="text-info">Password:</label><br>
					<input type="text" name="password" id="password" class="form-control">
				</div>							
				<div class="form-group">	
					<input type="submit" name="login" class="btn btn-info btn-md" value="Login">
					Haven't account? <a href="register.php" class="text-info">Register</a> here.
				</div>
				<div class="form-group">	
					test login: user@coderszine.com<br>
					password: 123
				</div>
			</form>
		</div>
	</div>
</div>

We will implement user login functionality by calling login() method from class User.php.

$user = new User();
$message = '';
if(isset($_POST['login'])){
	$message = $user->login();	
	if(!$message) {
		header("Location:index.php");
	}
}

In class User.php, we will implement login() method to handle user login.

public function login(){
	$message = '';
	if(!empty($_POST['email']) && !empty($_POST['password'])){
		$email = $_POST['email'];
		$password = md5($_POST['password']);
		$sqlQuery = "
		SELECT * 
		FROM ".$this->usersTable." 
		WHERE email='".$email."' AND password='".$password."'";
		$userData = $this->getData($sqlQuery);		
		if($userData){
			foreach ($userData as $user){
				$_SESSION['userLoggedIn'] = TRUE;
				$_SESSION['userID'] = $user['id'];	
				$_SESSION['name'] = $user['fname']." ".$user['lname'];	
			}				
		} else {							
			$message = 'Wrong email or password, please try again.'; 
		}
	}else{					
		$message = 'Enter email and password.'; 
	}  	
	return $message;
}	

Step4: Display Logged In User

In index.php file, we will design page to display logged in user details when user logged successfully otherwise login and register page link displayed.

<div class="container">
	<h2>Example: User Registration and Login System with PHP & MySQL</h2>	
	<div id="login-row" class="row justify-content-center align-items-center">			
		<div id="login-column" class="col-md-6">
			<br><br>
			<?php if(!empty($_SESSION['userLoggedIn']) && $_SESSION['userLoggedIn'] == TRUE) { ?> Logged in <strong><?php echo $_SESSION['name']; ?></strong> | <a href="logout.php" class="text-info">Logout</a> <?php } else { ?><a href="login.php" class="text-info">Login</a> | <a href="register.php" class="text-info">Register</a> <?php } ?>					
		</div>
	</div>
</div>

Step5: Implement User Logout Functionality

In logout.php file, we will implement user logout functionality and redirect to main page.

<?php
session_start();
session_destroy();
header("Location:index.php");
?>

Step6: Create User Class with Methods

We will create class User.php and implement MySQL database connection and user methods to perform user login and registration functionality.

<?php
session_start();
class User {
	private $host  = 'localhost';
    private $user  = 'root';
    private $password   = "";
    private $database  = "coderszine_demo";
	private $usersTable = 'users';	
	private $dbConnect = false;
    public function __construct(){
        if(!$this->dbConnect){ 
            $conn = new mysqli($this->host, $this->user, $this->password, $this->database);
            if($conn->connect_error){
                die("Error failed to connect to MySQL: " . $conn->connect_error);
            }else{
                $this->dbConnect = $conn;
            }
        }
    }
	private function getData($sqlQuery) {
		$result = mysqli_query($this->dbConnect, $sqlQuery);
		if(!$result){
			die('Error in query: '. mysqli_error());
		}
		$data= array();
		while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
			$data[]=$row;            
		}
		return $data;
	}
	private function getNumRows($sqlQuery) {
		$result = mysqli_query($this->dbConnect, $sqlQuery);
		if(!$result){
			die('Error in query: '. mysqli_error());
		}
		$numRows = mysqli_num_rows($result);
		return $numRows;
	}	
	public function login(){
		$message = '';
		if(!empty($_POST['email']) && !empty($_POST['password'])){
			$email = $_POST['email'];
			$password = md5($_POST['password']);
			$sqlQuery = "
			SELECT * 
			FROM ".$this->usersTable." 
			WHERE email='".$email."' AND password='".$password."'";
			$userData = $this->getData($sqlQuery);		
			if($userData){
				foreach ($userData as $user){
					$_SESSION['userLoggedIn'] = TRUE;
					$_SESSION['userID'] = $user['id'];	
					$_SESSION['name'] = $user['fname']." ".$user['lname'];	
				}				
			} else {							
				$message = 'Wrong email or password, please try again.'; 
			}
		}else{					
			$message = 'Enter email and password.'; 
		}  	
		return $message;
	}	
	public function register(){		
		$message = '';
		if(!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['phone']) && !empty($_POST['password']) && !empty($_POST['cpassword'])){		
			if($_POST['password'] !== $_POST['cpassword']){
				$message = 'Confirm password must match with the password.'; 
			}else {
				$sqlQuery = "
					SELECT * 
					FROM ".$this->usersTable." 
					WHERE email='".$_POST['email']."'";
				$result = mysqli_query($this->dbConnect, $sqlQuery);
				$userEmailExist = mysqli_num_rows($result);
				if($userEmailExist){					
					$message = 'Email already exists, please use another email.';
				}else{
					$insertUser = "
						INSERT INTO ".$this->usersTable." (fname, lname, email, phone, password) 
						VALUES ('".$_POST['fname']."', '".$_POST['lname']."', '".$_POST['email']."', '".$_POST['phone']."', '".md5($_POST['password'])."')";
					$userInserted = mysqli_query($this->dbConnect, $insertUser);					
					if($userInserted){						
						$message = 'You have registered successfully, <a href="login.php">log in</a> with your credentials.';
					}else{						
						$message = 'Some problem occurred, please try again.';
					}
				}
			}			
		} else {			
			$message = 'All fields are mandatory, please fill all the fields.'; 
		}	
		return $message;
	}
}
?>

You may also like:

You can view the live demo from the Demo link and can download the source from the Download link below.
Demo Download