How To Create User Login and Registration in PHP with MySQL
2 min readLogin and Registration in PHP are essential parts of any website in PHP. Here we will learn the following points in this tutorial on How you can build a simple, lightweight user registration and login in PHP with MySQL database.
User Registration
user-registration.php
<?php
use tutorial\Member;
if (! empty($_POST["signup-btn"])) {
require_once './Model/Member.php';
$member = new Member();
$registrationResponse = $member->registerMember();
}
?>
<HTML>
<HEAD>
<TITLE>https://sarveshpathak.com/</TITLE>
<link href="assets/css/tutorial-style.css" type="text/css"
rel="stylesheet" />
<link href="assets/css/user-registration.css" type="text/css"
rel="stylesheet" />
<script src="vendor/jquery/jquery-3.3.1.js" type="text/javascript"></script>
</HEAD>
<BODY>
<div class="tutorial-container">
<div class="sign-up-container">
<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">New User Registration</div>
<?php
if (! empty($registrationResponse["status"])) {
?>
<?php
if ($registrationResponse["status"] == "error") {
?>
<div class="server-response error-msg"><?php echo $registrationResponse["message"]; ?></div>
<?php
} else if ($registrationResponse["status"] == "success") {
?>
<div class="server-response success-msg"><?php echo $registrationResponse["message"]; ?></div>
<?php
}
?>
<?php
}
?>
<div class="error-msg" id="error-msg"></div>
<div class="row">
<div class="inline-block">
<div class="form-label">
Enter Your 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">
Enter Your 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">
Enter Your Password<span class="required error" id="signup-password-info"></span>
</div>
<input class="input-box-330" type="password"
name="signup-password" id="signup-password">
</div>
</div>
<div class="row">
<div class="inline-block">
<div class="form-label">
ReEnter Your Password<span class="required error"
id="confirm-password-info"></span>
</div>
<input class="input-box-330" type="password"
name="confirm-password" id="confirm-password">
</div>
</div>
<div class="row">
<input class="btn" type="submit" name="signup-btn"
id="signup-btn" value="Sign up">
</div>
<div class="row">
<div class="inline-block">
<div class="form-label">
https://sarveshpathak.com/
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<script>
function signupValidation() {
var valid = true;
$("#username").removeClass("error-field");
$("#email").removeClass("error-field");
$("#password").removeClass("error-field");
$("#confirm-password").removeClass("error-field");
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])?)*$/;
$("#username-info").html("").hide();
$("#email-info").html("").hide();
if (UserName.trim() == "") {
$("#username-info").html("required.").css("color", "#ee0000").show();
$("#username").addClass("error-field");
valid = false;
}
if (email == "") {
$("#email-info").html("required").css("color", "#ee0000").show();
$("#email").addClass("error-field");
valid = false;
} else if (email.trim() == "") {
$("#email-info").html("Invalid email address.").css("color", "#ee0000").show();
$("#email").addClass("error-field");
valid = false;
} else if (!emailRegex.test(email)) {
$("#email-info").html("Invalid email address.").css("color", "#ee0000")
.show();
$("#email").addClass("error-field");
valid = false;
}
if (Password.trim() == "") {
$("#signup-password-info").html("required.").css("color", "#ee0000").show();
$("#signup-password").addClass("error-field");
valid = false;
}
if (ConfirmPassword.trim() == "") {
$("#confirm-password-info").html("required.").css("color", "#ee0000").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>
User Registration CSS
.sign-up-container {
border: 1px solid;
border-color: #9a9a9a;
border-radius: 4px;
padding: 10px;
width: 350px;
margin: 50px auto;
box-shadow: 0 1rem 9rem 9px rgb(0 0 0 / 18%) !important;
border: 1px solid #cbcbcb;
background: #eaeaea;
}
.page-header {
float: right;
}
.login-signup {
margin: 10px;
text-decoration: none;
float: right;
}
.login-signup a {
text-decoration: none;
font-weight: 700;
}
.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: #ee0000;
padding: 0px;
background: none;
border: #ee0000;
}
.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;
}
Output
Login Page
<?php
use tutorial\Member;
if (! empty($_POST["login-btn"])) {
require_once __DIR__ . '/Model/Member.php';
$member = new Member();
$loginResult = $member->loginMember();
}
?>
<HTML>
<HEAD>
<TITLE>https://sarveshpathak.com/</TITLE>
<link href="assets/css/tutorial-style.css" type="text/css"
rel="stylesheet" />
<link href="assets/css/user-registration.css" type="text/css"
rel="stylesheet" />
<script src="vendor/jquery/jquery-3.3.1.js" type="text/javascript"></script>
</HEAD>
<BODY>
<div class="tutorial-container">
<div class="sign-up-container">
<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(!empty($loginResult)){?>
<div class="error-msg"><?php echo $loginResult;?></div>
<?php }?>
<div class="row">
<div class="inline-block">
<div class="form-label">
Enter Your 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">
Enter Your Password<span class="required error" id="login-password-info"></span>
</div>
<input class="input-box-330" type="password"
name="login-password" id="login-password">
</div>
</div>
<div class="row">
<input class="btn" type="submit" name="login-btn"
id="login-btn" value="Login">
</div>
<div class="row">
<div class="inline-block">
<div class="form-label">
https://sarveshpathak.com/
</div>
</div>
</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", "#ee0000").show();
$("#username").addClass("error-field");
valid = false;
}
if (Password.trim() == "") {
$("#login-password-info").html("required.").css("color", "#ee0000").show();
$("#login-password").addClass("error-field");
valid = false;
}
if (valid == false) {
$('.error-field').first().focus();
valid = false;
}
return valid;
}
</script>
</BODY>
</HTML>
User Login Output
Create a Model for the User Registration and Login
<?php
namespace tutorial;
class Member
{
private $ds;
function __construct()
{
require_once __DIR__ . '/../lib/DataSource.php';
$this->ds = new DataSource();
}
public function isUsernameExists($username)
{
$query = 'SELECT * FROM tbl_users where username = ?';
$paramType = 's';
$paramValue = array(
$username
);
$resultArray = $this->ds->select($query, $paramType, $paramValue);
$count = 0;
if (is_array($resultArray)) {
$count = count($resultArray);
}
if ($count > 0) {
$result = true;
} else {
$result = false;
}
return $result;
}
public function isEmailExists($email)
{
$query = 'SELECT * FROM tbl_users where email = ?';
$paramType = 's';
$paramValue = array(
$email
);
$resultArray = $this->ds->select($query, $paramType, $paramValue);
$count = 0;
if (is_array($resultArray)) {
$count = count($resultArray);
}
if ($count > 0) {
$result = true;
} else {
$result = false;
}
return $result;
}
public function registerMember()
{
$isUsernameExists = $this->isUsernameExists($_POST["username"]);
$isEmailExists = $this->isEmailExists($_POST["email"]);
if ($isUsernameExists) {
$response = array(
"status" => "error",
"message" => "Username already exists."
);
} else if ($isEmailExists) {
$response = array(
"status" => "error",
"message" => "Email already exists."
);
} else {
if (! empty($_POST["signup-password"])) {
$hashedPassword = password_hash($_POST["signup-password"], PASSWORD_DEFAULT);
}
$query = 'INSERT INTO tbl_users (username, password, email) VALUES (?, ?, ?)';
$paramType = 'sss';
$paramValue = array(
$_POST["username"],
$hashedPassword,
$_POST["email"]
);
$memberId = $this->ds->insert($query, $paramType, $paramValue);
if (! empty($memberId)) {
$response = array(
"status" => "success",
"message" => "You have registered successfully."
);
}
}
return $response;
}
public function getMember($username)
{
$query = 'SELECT * FROM tbl_users where username = ?';
$paramType = 's';
$paramValue = array(
$username
);
$memberRecord = $this->ds->select($query, $paramType, $paramValue);
return $memberRecord;
}
public function loginMember()
{
$memberRecord = $this->getMember($_POST["username"]);
$loginPassword = 0;
if (! empty($memberRecord)) {
if (! empty($_POST["login-password"])) {
$password = $_POST["login-password"];
}
$hashedPassword = $memberRecord[0]["password"];
$loginPassword = 0;
if (password_verify($password, $hashedPassword)) {
$loginPassword = 1;
}
} else {
$loginPassword = 0;
}
if ($loginPassword == 1) {
session_start();
$_SESSION["username"] = $memberRecord[0]["username"];
session_write_close();
$url = "./home.php";
header("Location: $url");
} else if ($loginPassword == 0) {
$loginStatus = "Invalid username or password.";
return $loginStatus;
}
}
}
Data Base Config
This class is a wrapper for MySQL / mysqli with PreparedStatement for User Login and Registration in PHP example. You can use it in any of your PHP projects to connect with databases. It is available in the download source code linked at the end of this tutorial.
<?php
namespace tutorial;
class DataSource
{
const HOST = 'localhost';
const USERNAME = 'root';
const PASSWORD = '201819';
const DATABASENAME = 'tutorial';
private $conn;
function __construct()
{
$this->conn = $this->getConnection();
}
public function getConnection()
{
$conn = new \mysqli(self::HOST, self::USERNAME, self::PASSWORD, self::DATABASENAME);
if (mysqli_connect_errno()) {
trigger_error("Problem with connecting to database.");
}
$conn->set_charset("utf8");
return $conn;
}
public function getPdoConnection()
{
$conn = FALSE;
try {
$dsn = 'mysql:host=' . self::HOST . ';dbname=' . self::DATABASENAME;
$conn = new \PDO($dsn, self::USERNAME, self::PASSWORD);
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
} catch (\Exception $e) {
exit("PDO Connect Error: " . $e->getMessage());
}
return $conn;
}
public function select($query, $paramType = "", $paramArray = array())
{
$stmt = $this->conn->prepare($query);
if (!empty($paramType) && !empty($paramArray)) {
$this->bindQueryParams($stmt, $paramType, $paramArray);
}
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultset[] = $row;
}
}
if (!empty($resultset)) {
return $resultset;
}
}
public function insert($query, $paramType, $paramArray)
{
$stmt = $this->conn->prepare($query);
$this->bindQueryParams($stmt, $paramType, $paramArray);
$stmt->execute();
$insertId = $stmt->insert_id;
return $insertId;
}
public function execute($query, $paramType = "", $paramArray = array())
{
$stmt = $this->conn->prepare($query);
if (!empty($paramType) && !empty($paramArray)) {
$this->bindQueryParams($stmt, $paramType, $paramArray);
}
$stmt->execute();
}
public function bindQueryParams($stmt, $paramType, $paramArray = array())
{
$paramValueReference[] = &$paramType;
for ($i = 0; $i < count($paramArray); $i++) {
$paramValueReference[] = &$paramArray[$i];
}
call_user_func_array(array(
$stmt,
'bind_param'
), $paramValueReference);
}
public function getRecordCount($query, $paramType = "", $paramArray = array())
{
$stmt = $this->conn->prepare($query);
if (!empty($paramType) && !empty($paramArray)) {
$this->bindQueryParams($stmt, $paramType, $paramArray);
}
$stmt->execute();
$stmt->store_result();
$recordCount = $stmt->num_rows;
return $recordCount;
}
}
Logout
This is the logout script for User Login and Registration in PHP.. You can use it in any of your PHP projects. It clears the complete user session and redirects the user to the index page.
<?php
// clear all the session variables and redirect to index
session_start();
session_unset();
session_write_close();
$url = "./index.php";
header("Location: $url");?>
MySQL database script
This is the script to create a table with five collum for this example of User Login and Registration in PHP. You can add more collum as per your requirement.
Table structure for table `tbl_users`
--
CREATE TABLE `tbl_users` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(200) NOT NULL,
`email` varchar(255) NOT NULL,
`create_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tbl_users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tbl_users`
--
ALTER TABLE `tbl_users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
COMMIT;
Home.php
<?php
session_start();
if (isset($_SESSION["username"])) {
$username = $_SESSION["username"];
session_write_close();
} else {
session_unset();
session_write_close();
$url = "./index.php";
header("Location: $url");
}
?>
<HTML>
<HEAD>
<TITLE>https://sarveshpathak.com/</TITLE>
<link href="assets/css/tutorial-style.css" type="text/css"
rel="stylesheet" />
<link href="assets/css/user-registration.css" type="text/css"
rel="stylesheet" />
</HEAD>
<BODY>
<div class="tutorial-container">
<div class="page-header">
<span class="login-signup"><a href="logout.php">Logout</a></span>
</div>
<div class="page-content">Welcome <?php echo $username;?></div>
</div>
</BODY>
</HTML>
index.php
<?php
require_once __DIR__ . "/login.php";