The User Registration and Login is an important feature of any web projects. In which user’s are allowed to register themselves to manage their account and provided roles to allow access to particular section.
So if your’re looking for user registration and login solution then you’re here at right place. In this tutorial you will learn how to develop user login and registration system with PHP and MySQL to use in any web project.
You can also enhance user login functionality with features like user login with OTP and user login with remember me password feature and
user password reset functionality. You can also create complete user management system with PHP & MySQL to manage user functionality with admin panel.
We will cover this tutorial in easy steps with live demo to handle complete user registration and login functionality with server side validation. You can also download the complete register and login script created with PHP and MySQL.
Also, read:
Let’s start implementing the user login and registration functionality with PHP and MySQL. Before you begin, take a look on files structure. We need following files for this tutorial.
- db_connect.php
- index.php
- login.php
- register.php
- logout.php
1. Create Database Table
In this tutorial we will need a database table to store user details. So we will create table users to store user information.
CREATE TABLE IF NOT EXISTS `users` ( `uid` int(11) NOT NULL AUTO_INCREMENT, `user` varchar(255) DEFAULT NULL, `pass` varchar(100) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `profile_photo` varchar(200) DEFAULT NULL, PRIMARY KEY (`uid`), UNIQUE KEY `username` (`user`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
2. Create Database Connection
We will create a PHP file db_connect.php to make connection with MySQL database.
<?php /* Database connection start */ $servername = "localhost"; $username = "root"; $password = ""; $dbname = "demos"; $conn = mysqli_connect($servername, $username, $password, $dbname); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } ?>
3. Create Main HTML for Login/Register
First we will create main file index.php to display Login/Register link. We will also display logged in user details on this page instead of Login/Register link when user successfully logged in.
<div class="container"> <h2>Example: Login and Registration Script with PHP, MySQL</h2> <div class="collapse navbar-collapse" > <ul class="nav navbar-nav navbar-left"> <?php if (isset($_SESSION['user_id'])) { ?> <li><p class="navbar-text"><strong>Welcome!</strong> You're signed in as <strong><?php echo $_SESSION['user_name']; ?></strong></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>
4. Create User Register Form HTML
Now we will create register.php file and create register Form HTML.
<div class="container"> <h2>Example: Login and Registration Script with PHP, MySQL</h2> <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($uname_error)) echo $uname_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($success_message)) { echo $success_message; } ?></span> <span class="text-danger"><?php if (isset($error_message)) { echo $error_message; } ?></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>
5. User Register Functionality with Form Validation
Now in same register.php file, we will handle user registration functionality by validating form input values like user name, email password and user store details in MySQL database table users
<?php include_once("db_connect.php"); session_start(); if(isset($_SESSION['user_id'])) { header("Location: index.php"); } $error = false; if (isset($_POST['signup'])) { $name = mysqli_real_escape_string($conn, $_POST['name']); $email = mysqli_real_escape_string($conn, $_POST['email']); $password = mysqli_real_escape_string($conn, $_POST['password']); $cpassword = mysqli_real_escape_string($conn, $_POST['cpassword']); if (!preg_match("/^[a-zA-Z ]+$/",$name)) { $error = true; $uname_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($conn, "INSERT INTO users(user, email, pass) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) { $success_message = "Successfully Registered! <a href='login.php'>Click here to Login</a>"; } else { $error_message = "Error in registering...Please try again later!"; } } } ?>
6. Create User Login Form HTML
Now we will create login.php file and create user login Form HTML.
<div class="container"> <h2>Example: Login and Registration Script with PHP, MySQL</h2> <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($error_message)) { echo $error_message; } ?></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>
7. User Login Functionality with Form Validation
Now in same login.php file, we will handle user login functionality with from validation and get user details from MySQL database table users. If user login successful, then stored user id and user name in SESSION variables to check for user login status and redirected to index.php to display user as logged in with user details and Logout link.
<?php session_start(); include_once("db_connect.php"); if(isset($_SESSION['user_id'])!="") { header("Location: index.php"); } if (isset($_POST['login'])) { $email = mysqli_real_escape_string($conn, $_POST['email']); $password = mysqli_real_escape_string($conn, $_POST['password']); $result = mysqli_query($conn, "SELECT * FROM users WHERE email = '" . $email. "' and pass = '" . md5($password). "'"); if ($row = mysqli_fetch_array($result)) { $_SESSION['user_id'] = $row['uid']; $_SESSION['user_name'] = $row['user']; header("Location: index.php"); } else { $error_message = "Incorrect Email or Password!!!"; } } ?>
8. User Logout Functionality
Now finally in logout.php, we will handle user logout functionality by unset SESSION variables to make user logout.
<?php ob_start(); session_start(); if(isset($_SESSION['user_id'])) { session_destroy(); unset($_SESSION['user_id']); unset($_SESSION['user_name']); header("Location: index.php"); } else { header("Location: index.php"); } ?>
You may also like:
- User Management System with PHP & MySQL
- Datatables Add Edit Delete with Ajax, PHP & MySQL
- Build Helpdesk System with jQuery, PHP & MySQL
- Build Online Voting System with PHP & MySQL
- School Management System with PHP & MySQL
- DataTables Add Edit Delete with CodeIgniter
- Create RESTful API using CodeIgniter
- Build Reusable Captcha Script with PHP
- Product Search Filtering using Ajax, PHP & MySQL
- Image Upload and Crop in Modal with jQuery, PHP & MySQL
- Build Push Notification System with PHP & MySQL
- Project Management System with PHP and MySQL
- Hospital Management System with PHP & MySQL
- Build Newsletter System with PHP and MySQL
- Skeleton Screen Loading Effect with Ajax and PHP
- Build Discussion Forum with PHP and MySQL
- Customer Relationship Management (CRM) System with PHP & MySQL
- Online Exam System with PHP & MySQL
- Expense Management System with PHP & MySQL
You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download
Hi,
thanks for the script.
Can you help me with this issue?
Warning: include(../container.php): failed to open stream: No such file or directory in /Library/WebServer/Documents/Login/login.php on line 24
Warning: include(): Failed opening ‘../container.php’ for inclusion (include_path=’.:’) in /Library/WebServer/Documents/Login/login.php on line 24
Best regards,
Mergim Alija
Please check these file path and fix them. thanks!
after executing your downloaded code, it is not logging out after refreshing the webpage means if someone copies the URL to another browser tab (in the LOGGED IN State), it opens the User Welcome Page without asking any prompt to login again.
kindly help me!
The login never logout when you refresh page. The logout only happen when cookie expired or logout from logout button. thanks!
its really useful script! Thanks
Can you provide the code to reset the password and change the password.
I need it urgently..
It will be a great help from your side!
You can download the full project from download link. thanks!
Great article. I’m experiencing some of these issues as well..
Can you add the code of change password and forgot password ?
I will try to add change password feature in future. Thanks!
Hi, i have used mysqli_real_escape_string(), but getting issue with it. What alternate option you suggest for this ?
Thanks
mysqli_real_escape_string is used to avoid SQL injection attach. if you’re facing issue with mysqli_real_escape_string, then you can use some different approach according to your requirement. Check PHP functions like strip_tags(), htmlspecialchars() etc to use according to your requirement. Thanks!