The login system allows the user to create and log in to their account for accessing the website content. The login system is a key feature for every membership website. If you want to restrict access to the website content and allow only the logged-in user to access the content, user login functionality need to be implemented. User registration and login system can be integrated easily with PHP and MySQL. In this tutorial, we’ll show you how to build a secure login system with PHP and MySQL.
In this PHP login system script, we will implement the following functionality with PHP and MySQL.
Before getting started to build User Login System with PHP, take a look at the file structure.
php_login_system_with_mysql/ ├── User.class.php ├── userAccount.php ├── index.php ├── registration.php └── css/ └── style.css
A table is required to store account details in the database. The following SQL creates a users
table in the MySQL database.
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(50) 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` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Block',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
User Class handles all the database-related operations (Connect, Fetch and Insert) with PHP and MySQL.
$dbHost
), username ($dbUsername
), password ($dbPassword
), and name ($dbName
) as per the MySQL database credentials.<?php
/*
* User Class
* This class is used for database related (connect fetch, and insert) operations
* @author CodexWorld.com
* @url https://www.codexworld.com
* @license https://www.codexworld.com/license
*/
class User{
private $dbHost = "localhost";
private $dbUsername = "root";
private $dbPassword = "root";
private $dbName = "codexworld";
private $userTbl = "users";
public function __construct(){
if(!isset($this->db)){
// Connect to the database
$conn = new mysqli($this->dbHost, $this->dbUsername, $this->dbPassword, $this->dbName);
if($conn->connect_error){
die("Failed to connect with MySQL: " . $conn->connect_error);
}else{
$this->db = $conn;
}
}
}
/*
* Returns rows from the database based on the conditions
* @param string name of the table
* @param array select, where, order_by, limit and return_type conditions
*/
public function getRows($conditions = array()){
$sql = 'SELECT ';
$sql .= array_key_exists("select",$conditions)?$conditions['select']:'*';
$sql .= ' FROM '.$this->userTbl;
if(array_key_exists("where",$conditions)){
$sql .= ' WHERE ';
$i = 0;
foreach($conditions['where'] as $key => $value){
$pre = ($i > 0)?' AND ':'';
$sql .= $pre.$key." = '".$value."'";
$i++;
}
}
if(array_key_exists("order_by",$conditions)){
$sql .= ' ORDER BY '.$conditions['order_by'];
}
if(array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['start'].','.$conditions['limit'];
}elseif(!array_key_exists("start",$conditions) && array_key_exists("limit",$conditions)){
$sql .= ' LIMIT '.$conditions['limit'];
}
$result = $this->db->query($sql);
if(array_key_exists("return_type",$conditions) && $conditions['return_type'] != 'all'){
switch($conditions['return_type']){
case 'count':
$data = $result->num_rows;
break;
case 'single':
$data = $result->fetch_assoc();
break;
default:
$data = '';
}
}else{
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}
}
return !empty($data)?$data:false;
}
/*
* Insert data into the database
* @param string name of the table
* @param array the data for inserting into the table
*/
public function insert($data){
if(!empty($data) && is_array($data)){
$columns = '';
$values = '';
$i = 0;
if(!array_key_exists('created',$data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists('modified',$data)){
$data['modified'] = date("Y-m-d H:i:s");
}
foreach($data as $key=>$val){
$pre = ($i > 0)?', ':'';
$columns .= $pre.$key;
$values .= $pre."'".$val."'";
$i++;
}
$query = "INSERT INTO ".$this->userTbl." (".$columns.") VALUES (".$values.")";
$insert = $this->db->query($query);
return $insert?$this->db->insert_id:false;
}else{
return false;
}
}
}
This server-side script handles the registration, authentication, and logout request which comes from index.php
and registration.php
. The User Class (User.class.php
) is used to fetch and insert user account data from/to the database.
signupSubmit
– If sign up request is submitted, input data is inserted in the database after the validation.loginSubmit
– If login request is submitted, the system checks if any record is exists in the database with the given email and password.logoutSubmit
– If logout request is submitted, system log the user out from their account.<?php
// Start session
session_start();
// Load and initialize user class
include 'User.class.php';
$user = new User();
$postData = $statusMsg = $valErr = '';
$status = 'error';
$redirectURL = 'index.php';
if(isset($_POST['signupSubmit'])){
$redirectURL = 'registration.php';
// Get user's input
$postData = $_POST;
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$password = trim($_POST['password']);
$confirm_password = trim($_POST['confirm_password']);
// Validate form fields
if(empty($first_name)){
$valErr .= 'Please enter your first name.<br/>';
}
if(empty($last_name)){
$valErr .= 'Please enter your last name.<br/>';
}
if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
$valErr .= 'Please enter a valid email.<br/>';
}
if(empty($phone)){
$valErr .= 'Please enter your phone no.<br/>';
}
if(empty($password)){
$valErr .= 'Please enter login password.<br/>';
}
if(empty($confirm_password)){
$valErr .= 'Please confirm your password.<br/>';
}
if($password !== $confirm_password){
$valErr .= 'Confirm password should be matched with the password.<br/>';
}
// Check whether user inputs are empty
if(empty($valErr)){
// Check whether the user already exists with the same email in the database
$prevCon['where'] = array(
'email'=>$_POST['email']
);
$prevCon['return_type'] = 'count';
$prevUser = $user->getRows($prevCon);
if($prevUser > 0){
$statusMsg = 'Email already registered, please use another email.';
}else{
// Insert user data in the database
$password_hash = md5($password);
$userData = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'password' => $password_hash,
'phone' => $phone
);
$insert = $user->insert($userData);
if($insert){
$status = 'success';
$statusMsg = 'Your account has been registered successfully, login to the account.';
$postData = '';
$redirectURL = 'index.php';
}else{
$statusMsg = 'Something went wrong, please try again after some time.';
}
}
}else{
$statusMsg = '<p>Please fill all the mandatory fields:</p>'.trim($valErr, '<br/>');
}
// Store registration status into the SESSION
$sessData['postData'] = $postData;
$sessData['status']['type'] = $status;
$sessData['status']['msg'] = $statusMsg;
$_SESSION['sessData'] = $sessData;
// Redirect to the home/registration page
header("Location: $redirectURL");
}elseif(isset($_POST['loginSubmit'])){
// Get user's input
$postData = $_POST;
$email = trim($_POST['email']);
$password = trim($_POST['password']);
// Validate form fields
if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
$valErr .= 'Please enter a valid email.<br/>';
}
if(empty($password)){
$valErr .= 'Please enter your password.<br/>';
}
// Check whether user inputs are empty
if(empty($valErr)){
// Check whether the user account exists with active status in the database
$password_hash = md5($password);
$conditions['where'] = array(
'email' => $email,
'password' => $password_hash,
'status' => 1
);
$conditions['return_type'] = 'single';
$userData = $user->getRows($conditions);
if(!empty($userData)){
$status = 'success';
$statusMsg = 'Welcome '.$userData['first_name'].'!';
$postData = '';
$sessData['userLoggedIn'] = TRUE;
$sessData['userID'] = $userData['id'];
}else{
$statusMsg = 'Wrong email or password, please try again!';
}
}else{
$statusMsg = '<p>Please fill all the mandatory fields:</p>'.trim($valErr, '<br/>');
}
// Store login status into the SESSION
$sessData['postData'] = $postData;
$sessData['status']['type'] = $status;
$sessData['status']['msg'] = $statusMsg;
$_SESSION['sessData'] = $sessData;
// Redirect to the home page
header("Location: $redirectURL");
}elseif(!empty($_REQUEST['logoutSubmit'])){
// Remove session data
unset($_SESSION['sessData']);
session_destroy();
// Store logout status into the SESSION
$sessData['status']['type'] = 'success';
$sessData['status']['msg'] = 'You have logout successfully!';
$_SESSION['sessData'] = $sessData;
// Redirect to the home page
header("Location: $redirectURL");
}else{
// Redirect to the home page
header("Location: $redirectURL");
}
The following HTML form elements allow to input the account informations (name, email, password, etc.) for registration.
userAccount.php
) to process the signup request.
<?php
// Start session
session_start();
// Get data from session
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
// Get status from session
if(!empty($sessData['status']['msg'])){
$statusMsg = $sessData['status']['msg'];
$status = $sessData['status']['type'];
unset($_SESSION['sessData']['status']);
}
$postData = array();
if(!empty($sessData['postData'])){
$postData = $sessData['postData'];
unset($_SESSION['postData']);
}
?>
<!-- Status message -->
<?php if(!empty($statusMsg)){ ?>
<div class="status-msg <?php echo $status; ?>"><?php echo $statusMsg; ?></div>
<?php } ?>
<div class="regisFrm">
<form action="userAccount.php" method="post">
<input type="text" name="first_name" placeholder="FIRST NAME" value="<?php echo !empty($postData['first_name'])?$postData['first_name']:''; ?>" required="">
<input type="text" name="last_name" placeholder="LAST NAME" value="<?php echo !empty($postData['last_name'])?$postData['last_name']:''; ?>" required="">
<input type="email" name="email" placeholder="EMAIL" value="<?php echo !empty($postData['email'])?$postData['email']:''; ?>" required="">
<input type="text" name="phone" placeholder="PHONE NUMBER" value="<?php echo !empty($postData['phone'])?$postData['phone']:''; ?>" required="">
<input type="password" name="password" placeholder="PASSWORD" required="">
<input type="password" name="confirm_password" placeholder="CONFIRM PASSWORD" required="">
<div class="send-button">
<input type="submit" name="signupSubmit" value="CREATE ACCOUNT">
</div>
</form>
</div>
Initially, the login form is displayed to allow the user signin with email and password.
<?php
// Start session
session_start();
// Get data from session
$sessData = !empty($_SESSION['sessData'])?$_SESSION['sessData']:'';
// Get status from session
if(!empty($sessData['status']['msg'])){
$statusMsg = $sessData['status']['msg'];
$status = $sessData['status']['type'];
unset($_SESSION['sessData']['status']);
}
$postData = array();
if(!empty($sessData['postData'])){
$postData = $sessData['postData'];
unset($_SESSION['postData']);
}
// If the user already logged in
if(!empty($sessData['userLoggedIn']) && !empty($sessData['userID'])){
include_once 'User.class.php';
$user = new User();
$conditions['where'] = array(
'id' => $sessData['userID']
);
$conditions['return_type'] = 'single';
$userData = $user->getRows($conditions);
}
?>
<?php if(!empty($userData)){ ?>
<h2>Welcome <?php echo $userData['first_name']; ?>!</h2>
<a href="userAccount.php?logoutSubmit=1" class="logout">Logout</a>
<div class="regisFrm">
<p><b>Name: </b><?php echo $userData['first_name'].' '.$userData['last_name']; ?></p>
<p><b>Email: </b><?php echo $userData['email']; ?></p>
<p><b>Phone: </b><?php echo $userData['phone']; ?></p>
</div>
<?php }else{ ?>
<h2>Login to Your Account</h2>
<!-- Status message -->
<?php if(!empty($statusMsg)){ ?>
<div class="status-msg <?php echo $status; ?>"><?php echo $statusMsg; ?></div>
<?php } ?>
<div class="regisFrm">
<form action="userAccount.php" method="post">
<input type="email" name="email" placeholder="EMAIL" value="<?php echo !empty($postData['email'])?$postData['email']:''; ?>" required="">
<input type="password" name="password" placeholder="PASSWORD" required="">
<div class="send-button">
<input type="submit" name="loginSubmit" value="LOGIN">
</div>
</form>
<p>Don't have an account? <a href="registration.php">Register</a></p>
</div>
<?php } ?>
Hope this step-by-step tutorial and example script help you to implement the registration and login system in the PHP web application. You can integrate user login functionality in the website with PHP and MySQL using SESSION. Also, you can extend the User Class to build an advanced user authentication system and user management system.
Next Part: Forgot Password Recovery Functionality Implementation in Login System with PHP and MySQL
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Keep on working, great job!
Thanks. Your tutorial helped me a lot. Keep it up.
Thank you for this great job, please how do i need code for one person to register many people and submit it in one form.
hello very good work, how can i put code like this (!preg_match(“/([\w\-]+\@[\w\-]+\.[\w\-]+)/”,$value)) for the email? thanks
how to attach the php file with css stylesheet
Thanks for the tutorial
Thank you so much for a wonderful Tutorial and the source code. It helped me a lot. You are doing such a fabulous job. Looking forward more projects.
i have already created a number of web pages how do i implement this on all of them?
This is such a great work, more knowledge.
i’m trying to setup a login/registration system
where users are registered to different department and while login in, the menus displayed on the index page will be determined by the department of registration and login (while login in, the condition of username, password and department as to be true with registration) for each user.
Many thanks.
Please send your modification requirements to our support team at support@codexworld.com.
thanks a lot .this code perfectly running ,not even single errors are coming.
Hey, I’m loving the script. Can you confirm how i can check session is active on individual pages or direct back to login?
hello sir amazing script but one thing could you add email activation to avoid false registration
How can i make so only a certain ID can access a website?
thanks for the tutorial
Thank you for the tutorial . I have a major challenge, I’m using two radio buttons to display two different registration forms.On selection of one radio button, I want the form to save to a different table, likewise the other button. But I can’t seem to figure it out, since I’ve been experimenting on one radio button, but nothing on the form is saving to the database
In that case, send your requirements to our support team at support@codexworld.com.
Sir, how to add images I means upload image
To upload image in PHP, see this tutorial – https://www.codexworld.com/php-file-upload/
How to make the phone number as a data validation so that if we enter abc then something pop out saying that please enter correct phone number
You can validate the phone number easily with HTML5. Use type and pattern attribute in HTML input field for phone number validation, see the example code from here – https://www.codexworld.com/how-to/phone-number-validation-html5/
Great! Am a newbie, my challenges are:
A} how to blend the php files extentions wt main website html extention files.
b} where is the data base table created- @ the hosts Cpane l or one of the files to host.
please help me out how to connect the data base table
Good work and thanks a lot for sharing!
keep your good work
love your website
i want to work with you per my projects
add my skype id
Ion Vladescu | Microsoft & Cisco Trainer
Skype: ion.vladescu
Thank you so much for the code, it was really helpful.
I’d like to know What should we replace the varibale “$conditions” with..?
Greetings Sir,
How to check email already exists validation using JAVASCRIPT and AJAX. In Ajax i want To Post the page to the same page not at other location. I am having modal form. If am tring to do the same. Error message gets printed on home page instead of Modal Form kindly revert me asap.
Thanks for all your hard work it is much appreciated
may I ask how to use the select conditions
can you give a sample
many thanks