Websites play important role in business development. As you know, we can provide many services on our websites. Users can get services using an account. We create a login and registration system for this process.
In this tutorial, we will create a login and registration form using PHP PDO and oops concepts. We will use PDO-prepared statements for security purpose and to void SQL injection. We will validate every field while loging and registering to secure the MYSQL database. Object-oriented programming (OOPS) aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming.
We have created a registration and login system in procedural programming using PHP MYSQLI but this was a beginner tutorial. In this tutorial, we will create advanced registration and login system using PDO (PHP data object ) prepared statement and oops concepts.
How to create registration and login forms in PHP PDO and OOPS –
In oops concepts, we create functions inside the classes, and abstract concepts to create logic. We will create autoload file in PHP. The autoload function allows you to register multiple functions (or static methods from your own autoload class) that PHP will put into a stack/queue and call sequentially when a "new class" is declared. You have to declare your class in this autoload. Create your object and pass the database connection variable as a parameter during declaration time. The login and registration system must be validated for that, we will create a validation() function that will be used to validate every field – Please enter your first name, Enter your name in 3 characters at least, your username should be valid, and your email id should be a valid id, the password should be 6 or 8 characters long. You can set your minimum and maximum limit. We will create a sanitize() function to validate every field and remove unwanted symbols for string, int, Boolean, URL, and email. We will use the bootstrap framework. Bootstrap is used to make a responsive login and registration form.
Let’s create a login and registration form in PHP –
Create an MYSQL database table for login and registration -
First of all, we create the database table. Create a database table using the below query.
CREATE TABLE `users` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`fname` varchar(255) DEFAULT NULL,
`lname` varchar(255) DEFAULT NULL,
`username` varchar(300) DEFAULT NULL,
`email` varchar(300) DEFAULT NULL,
`password` varchar(300) DEFAULT NULL,
`created_date` datetime NOT NULL
);
The table name is “users”. We have created many fields like first name, last name, username, password, and registration date.
Create a connection between HTML and MYSQL database using PDO -
Now, we connect HTML to the MYSQL database using PHP PDO . Create a connection file.
config.php
<?php
define('DBNAME','web');
define('DBUSER','root');
define('DBPASS','');
define('DBHOST','localhost');
try {
$db = 'mysql:host=' .DBHOST . ';dbname=' . DBNAME.';utf8';
$db= new PDO($db,DBUSER,DBPASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
//echo "Your page is connected with database successfully..";
} catch(PDOException $e) {
echo "Issue -> Connection failed: " . $e->getMessage();
}
?>
In the above code, we have used the PHP PDO connection string and created a connection object. Kindly set your credentials according to your local server or live server.
The connection file has been created successfully.
PHP autoload file using spl_autoload_register() function -
Now, create an autoload file. We will use the spl_autoload_register() function. It's a magic function that helps you include/require files using a class name.
autoload.php
<?php session_start();
require_once("config.php");
spl_autoload_register(function($className){
require_once("classes/$className.php");
});
$getUser=new User($db);
?>
In the above code, we have included a config file. As you can see, we have added classes path.
Note – Kindly create a new folder – classes
We will create every class in this "classes" folder.
In this autoload, we have declared a class and created an object. If you create any other class then declare that class in autoload and create an object. We will use the object to call functions from the same class. We will not include class or function one by one. We will include an autload.php file and it will automatically call class.
Registration (Signup) form in PDO and OOPS -
Now, we will create a registration form. In other words, the registration form is known as the signup form so don’t be confused. We will create a signup form in the PHP OOPS concept. We will use bootstrap classes to make a responsive registration form.
signup.php –
<?php require_once("autoload.php");
if($getUser->is_loggedin())
{
header("location:account.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Signup - Techno Smarter</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-2">
</div>
<div class="col-sm-8">
<div class="form_container">
<img src="https://technosmarter.com/assets/images/logo.png" alt="Techno Smarter" class="logo img-fluid"> <br>
<?php
if(isset($_POST['submit_form']))
{
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$username=$_POST['username'];
$email=$_POST['email'];
$password=$_POST['password'];
$passwordConfirm=$_POST['passwordConfirm'];
$error=$getUser->validation($fname,$lname,$username,$email,$password,$passwordConfirm);
if($error==NULL) {
$result=$getUser->register($fname,$lname,$username,$email,$password);
if($result)
{
header("location:login.php?register=1");
}
else
{
$error[]='Something went wrong..';
}
}
if(isset($error)){
foreach($error as $err){
echo '<p class="errormsg">'.$err.'</p>';
}
}
}
?>
<form action="" method="post">
<div class="row">
<div class="col-sm-6 mb-3">
<div class="form-floating">
<input type="text" class="form-control" name="fname" id="floatingInput" placeholder="First Name" value="<?php if(isset($error)){echo $fname;}?>">
<label for="floatingInput">First Name</label>
</div>
</div>
<div class="col-sm-6 mb-3">
<div class="form-floating">
<input type="text" class="form-control" name="lname" id="floatingInput" placeholder="Last Name" value="<?php if(isset($error)){echo $lname;}?>">
<label for="floatingInput">Last Name</label>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6 mb-3">
<div class="form-floating">
<input type="text" class="form-control" name="username" id="floatingInput" placeholder="Username" value="<?php if(isset($error)){echo $username;}?>">
<label for="floatingInput">Username</label>
</div>
</div>
<div class="col-sm-6 mb-3">
<div class="form-floating">
<input type="text" class="form-control" name="email" id="floatingInput" placeholder="Email" value="<?php if(isset($error)){echo $email;}?>">
<label for="floatingInput">Email</label>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-sm-6 mb-3">
<div class="form-floating">
<input type="password" class="form-control" name="password" id="floatingInput" placeholder="Password">
<label for="floatingInput">Password </label>
</div>
</div>
<div class="col-sm-6 mb-3">
<div class="form-floating">
<input type="password" class="form-control" name="passwordConfirm" id="floatingInput" placeholder="Confirm Password">
<label for="floatingInput">Confirm Password</label>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col-sm-4"> </div>
<div class="col-sm-4" style="text-align: center;"><button type="submit" class="btn form_btn btn-primary" name="submit_form">Signup>></button></div>
<div class="col-sm-4"> </div>
</div>
</form>
<br>
<p>Have an account? <a href="login.php">Log in </a> </p>
</div>
</div>
<div class="col-sm-2">
</div>
</div>
</div>
</body>
</html>
In the above code, we have created a registration form using bootstrap. We have used bootstrap floating labels like the Google login form. As you can see, we have called the validation() and register() functions. The validation() function will validate every field value and the register() function will be used to insert user data into the MYSQL database. We have used PDO-prepared statements. Prepare an SQL query with empty values as placeholders with either a question mark or a variable name with a colon (:name ) preceding it for each value. Bind values or variables to the placeholders
Designing registration and login forms using stylesheet -
Now, we will design the registration form with the stylesheet.
style.css
body{
background:#EAE9E5;
}
.form_container{
margin-top: 12%;
background: #fff;
padding: 25px;
border: 1px solid #AEAEAF;
border-radius: 5px;
}
.form-control:focus
{
border: 1px solid #5136E8;
box-shadow:none;
}
.form_btn{
box-shadow: 0 1px 2px 0 rgba(0,0,0,.2);
border: none;
color: #fff;
width: 100%
}
.logo{
height: 50px;
width: auto;
display: block;
margin-left: auto;
margin-right: auto;
}
.field
{
font-weight: 700;
}
.errormsg{
margin: 2px auto;
border-radius: 5px;
border: 1px solid red;
background: pink;
text-align: left;
color: brown;
padding: 1px;
}
.successmsg{
margin: 5px auto;
border-radius: 5px;
border: 1px solid green;
background: #33CC00;
text-align: left;
color: white;
padding: 10px;
}
We have created CSS classes for the login form, registration form, and account page in the above stylesheet file.
Let's create classes and these functions.
First of all, ensure that you have created a "classes" folder.
Create an abstract class (PHP OOPS concept ) -
Now, create a first basic class. It will be an abstract class. Abstraction is a process of hiding the implementation details and showing only functionality to the user. An abstract class is created with an abstract keyword. We create our logics/methods in that class and use them in another child class by extending this abstract class. We will create the common functions in the abstract class and use them in every child class.
classes/Basic.php
<?php abstract class Basic{
public function get_date()
{
$date = new DateTime(null, new DateTimezone("Asia/Kolkata"));
$date=$date->format('Y-m-d H:i:s');
return $date;
}
public function sanitize($var,$type)
{
$filter = false;
switch($type)
{
case 'email':
$var = substr($var, 0, 254);
$filter = FILTER_VALIDATE_EMAIL;
break;
case 'int':
$filter = FILTER_VALIDATE_INT;
break;
case 'boolean':
$filter = FILTER_VALIDATE_BOOLEAN;
break;
case 'ip':
$filter = FILTER_VALIDATE_IP;
break;
case 'url':
$filter = FILTER_VALIDATE_URL;
break;
case 'string':
default:
$filter = FILTER_SANITIZE_STRING;
break;
}
return $filter= trim(filter_var($var, $filter));
}
public function easy_date($date)
{
return date('d M Y',strtotime($date));
}
}
?>
In the above class, we have created get_date() and sanitize() functions because these are mostly used functions in every class. We will extend the abstract class in the child class. As you know, PHP does not support multiple inheritance. You can understand these points in PHP OOPS concepts.
Create a User class (PHP OOPS concept ) -
Now, create another class for user registration. We will create validation() and register() functions in this user class.
classes/User.php
<?php Class User extends Basic
{
private $dbConnection;
function __construct($db)
{
$this->dbConnection = $db;
}
//register
public function validation($fname,$lname,$username,$email,$password,$passwordConfirm)
{
$fname=$this->sanitize($fname,'string');
$lname=$this->sanitize($lname,'string');
$username=$this->sanitize($username,'string');
$email=$this->sanitize($email,'email');
$password=$this->sanitize($password,'string');
$passwordConfirm=$this->sanitize($passwordConfirm,'string');
if(strlen($fname)<=2){
$error[] = 'Please enter First name using 3 charaters atleast.';
}
if(strlen($fname)>2)
{
if(!preg_match("/^[a-zA-Z\s]+$/", $fname)){
$error[] = 'First Name:Characters Only (No digits or special charaters) ';
}
}
if(strlen($fname)>20){
$error[] = 'First Name: Max length 20 Characters Not allowed';
}
if(strlen($lname) <=2){
$error[] = 'Please enter Last name using 3 charaters atleast.';
}
if(strlen($lname) >2)
{
if(!preg_match("/^[a-zA-Z\s]+$/", $lname)){
$error[] = 'Last Name:Characters Only (No digits or special charaters) ';
}
}
if(strlen($lname)>20){
$error[] = 'Last Name: Max length 20 Characters Not allowed';
}
if(strlen($username) <=2){
$error[] = 'Please enter Username using 3 charaters atleast.';
}
if(strlen($username) >2){
if(!preg_match("/^^[^0-9][a-z0-9]+([_-]?[a-z0-9])*$/", $username)){
$error[] = 'Invalid Entry for Username.Eg - myusername or myusername123';
}
}
if(strlen($username)>20){
$error[] = 'UserName: Max length 20 Not allowed';
}
if($email ==''){
$error[] = 'Please enter the email address.';
}
if($email !=''){
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i", $email)){
$error[] = 'Invalid Entry for Email.ie- username@domain.com';
}
}
$count_username=$sql= "SELECT count(*) FROM users WHERE username=:username";
$stmt = $this->dbConnection->prepare($sql);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$count_username = $stmt->fetchColumn();
if($count_username>0)
{
$error[] = 'Username already exists.';
}
$count_username=$sql= "SELECT count(*) FROM users WHERE email=:email";
$stmt = $this->dbConnection->prepare($sql);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$count_email= $stmt->fetchColumn();
if($count_email>0)
{
$error[] = 'Email already exists.';
}
if($password ==''){
$error[] = 'Please enter the password.';
}
if($password !=''){
if($passwordConfirm ==''){
$error[] = 'Please confirm the password.';
}
if(strlen($password)<6){
$error[] = 'The password should be 6 characters long.';
}
if(strlen($password)>20){
$error[] = 'Password: Max length 20 Characters Not allowed';
}
if($password != $passwordConfirm){
$error[] = 'Passwords do not match.';
}
}
if(isset($error))
{
return $error;
}
else
{
return $arrayName = [];
}
}
public function register($fname,$lname,$username,$email,$password)
{
$fname=$this->sanitize($fname,'string');
$fname=$this->sanitize($fname,'string');
$username=$this->sanitize($username,'string');
$email=$this->sanitize($email,'email');
$password=$this->sanitize($password,'string');
$sql = "INSERT INTO users(fname,lname,username,email,password,created_date) VALUES(:fname,:lname,:username,:email,:password,:created_date)";
$stmt = $this->dbConnection->prepare($sql);
$created_date=$this->get_date();
$options = array("cost"=>4);
$hashedpassword= password_hash($password,PASSWORD_BCRYPT,$options);
$stmt->bindParam(':fname',$fname, PDO::PARAM_STR);
$stmt->bindParam(':lname',$lname, PDO::PARAM_STR);
$stmt->bindParam(':username',$username, PDO::PARAM_STR);
$stmt->bindParam(':email',$email, PDO::PARAM_STR);
$stmt->bindParam(':password',$hashedpassword, PDO::PARAM_STR);
$stmt->bindParam(':created_date',$created_date, PDO::PARAM_STR);
$res=$stmt->execute();
if($res)
{
return true;
}
else
{
return false;
}
}
// login functions here
//account function here
}
?>
In the above class, we have created a validation() function to validate every field.
Validations for registration form fields –
1. Validation for form minimum value in the input box –
The user should enter the minimum value in the input box. You can set the minimum value for the input box.
Example -
if(strlen($fname)<3){ // Minimum
$error[] = 'Please enter First Name using 3 charaters atleast.';
}
2. Maximum value in the input box –
This is another validation of the input box that restricts users to enter the value in the registration form below a limit.
Example –
if(strlen($fname)>20){ // Max
$error[] = 'First Name: Max length 20 Characters Not allowed';
}
3. Registration form fields validation with regular expressions-
Regular expressionss help to validate the correct form of data. In the registration form, we use regular expressions according to a different type of data format.
Example-
Username - The username should not be started with digits.
The username should not be contained white space at the start and between the characters or digits.
This type of situation handles by the regular expressions –
if(!preg_match("/^^[^0-9][a-z0-9]+([_-]?[a-z0-9])*$/", $username)){
$erro5r[] = 'Invalid Entry for Username. Enter lowercase letters without any space and No number at the start- Eg - myusername, okuniqueuser or myusername123';
In the code above, we have used regular expression
/^^[^0-9][a-z0-9]+([_-]?[a-z0-9])*$/ inside the preg_match() function of PHP to match the requirements .
We will use regular expressions in the registration form.
Username or email already exists in the Registration form –
Duplicate data is a bad habit for registration forms. Every time many unknown users have registered with the same username or email. This is a really bad impression if you are going to create a registration form in PHP with the MYSQL database.
We will validate the username and email if already exists in PHP.
$count_username=$sql= "SELECT count(*) FROM users WHERE username=:username";
$stmt = $this->dbConnection->prepare($sql);
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$count_username = $stmt->fetchColumn();
if($count_username>0)
{
$error[] = 'Username already exists.';
}
$count_username=$sql= "SELECT count(*) FROM users WHERE email=:email";
$stmt = $this->dbConnection->prepare($sql);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$count_email= $stmt->fetchColumn();
if($count_email>0)
{
$error[] = 'Email already exists.';
}
In the code above, we are fetching the data from the database and checking if the username or email already exists in the database. If the username or email exists in the MySQL database then the data doesn't insert into the MYSQL database. It’s really important for the registration form in PHP.
Convert simple text password into the hash pattern in the Registration form–
The hash pattern is a difficult pattern to hack and remember by the user or another unknown hacker. The simple text password can be hacked by the hacker but we will convert the simple text password into the hash pattern. It will be more secure and cannot be hacked by the hacker.
We will use the password_hash() function of PHP in the registration form.
$options = array("cost"=>4);
$password = password_hash($password,PASSWORD_BCRYPT,$options);
Login form in PHP PDO and OOPS -
Now, create a login form in PHP OOPS.
login.php
<?php require_once("autoload.php");
if($getUser->is_loggedin())
{
header("location:account.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login - Techno Smarter</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-4">
</div>
<div class="col-sm-4">
<div class="form_container">
<img src="https://technosmarter.com/assets/images/logo.png" alt="Techno Smarter" class="logo img-fluid"> <br>
<?php
if(isset($_POST['submit_form']))
{
$login_var=$_POST['login_var'];
$password=$_POST['password'];
$check=$getUser->login($login_var,$password);
if($check)
{
header("location:account.php");
}
else
{
echo '<div class="errormsg">Invalid login credentials ,Please try again .. </div>';
}
}
if(isset($_GET['register']))
{
echo '<p class="successmsg">You have successfully registered.</p>';
}
if(isset($_GET['logged_out']))
{
echo '<p class="successmsg">You have logged out.</p>';
}
?>
<form action="" method="post">
<div class="form-floating mb-3">
<input type="text" name="login_var" value="<?php if(isset($check)){echo $login_var;}?>" class="form-control" id="floatingInput" placeholder="Username or Email" required>
<label for="floatingInput">Username or Email</label>
</div>
<div class="form-floating mb-3">
<input type="password" name="password" class="form-control" id="floatingPassword" placeholder="Password" required>
<label for="floatingPassword">Password</label>
</div>
<div class="row mb-3">
<div class="col-sm-12" style="text-align: center;"><button type="submit" class="btn form_btn btn-primary" name="submit_form">Login</button></div>
</div>
</form>
<p style="font-size: 12px;text-align: center;margin-top: 10px;"><a href="forgot-password.php" style="color: #00376b;">Forgot Password?</a> </p>
<br>
<p>Don't have an account? <a href="signup.php">Sign up</a> </p>
</div>
</div>
<div class="col-sm-4">
</div>
</div>
</div>
</body>
</html>
In the above code, we have called the login() function to verify user details like username, email, and hash password. If user details are correct, create a session or if user details are incorrect then display an invalid username and password error on the website page.
Create these functions inside the User class. Just copy and paste it inside the User class.
classes/User.php
public function login($login_var,$password){
$login_var=$this->sanitize($login_var,'string');
$password=$this->sanitize($password,'string');
$sql= "SELECT count(*) from users WHERE username=:username OR email=:email limit 1";
$stmt = $this->dbConnection->prepare($sql);
$stmt->bindParam(':username', $login_var, PDO::PARAM_STR);
$stmt->bindParam(':email', $login_var, PDO::PARAM_STR);
$stmt->execute();
$count_user= $stmt->fetchColumn();
if($count_user>0){
$sql= "SELECT id,password from users WHERE username=:username OR email=:email limit 1";
$stmt = $this->dbConnection->prepare($sql);
$stmt->bindParam(':username', $login_var, PDO::PARAM_STR);
$stmt->bindParam(':email', $login_var, PDO::PARAM_STR);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(password_verify($password,$row['password'])){
$_SESSION["logged_in"]="1";
$_SESSION["userid"]= $row['id'];
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public function is_loggedin(){
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true){
return true;
} }
public function logout(){
unset($_SESSION['logged_in']);
unset($_SESSION['userid']);
}
Kindly paste these functions inside the User class block of code (inside the class { }, after the register() function)
In the above code, we have created is_loggedin(), and logout() functions. the is_loggedin() function is used to check whether the user logged in or not. (login session created or not). The logout() function is used to unset the session variable (logout user).
Now, you can log in with the login form.
My account page in PHP -
After successful login, you will be redirected to the account page. The account page is known as my account page where users can own details and log out with a link.
Create an account page.
account.php
<?php require_once("autoload.php");
if(!$getUser->is_loggedin())
{
header("location:login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Account - Techno Smarter</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-sm-3">
</div>
<div class="col-sm-6">
<div class="form_container">
<img src="https://technosmarter.com/assets/images/logo.png" alt="Techno Smarter" class="logo img-fluid"> <br>
<?php
$row=$getUser->fetch_user($_SESSION['userid']);
?>
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-6" style="text-align:center;background: #DAF7A6 ">Hi 👋 <strong><?php echo $row['username'];?></strong></div>
<div class="col-sm-3"> <a href="logout.php"><span style="color:red;float: right;">(Logout)</span> </a></div>
</div>
<hr>
<div class="row">
<div class="col-sm-4"><div class="field">First Name:</div> </div>
<div class="col-sm-8"><?php echo $row['fname'];?></div>
</div>
<hr>
<div class="row">
<div class="col-sm-4"><div class="field">Last Name:</div></div>
<div class="col-sm-8"><?php echo $row['lname'];?></div>
</div>
<hr>
<div class="row">
<div class="col-sm-4"><div class="field">Email : </div></div>
<div class="col-sm-8"><?php echo $row['email'];?></div>
</div>
<hr>
<div class="row">
<div class="col-sm-4"><div class="field">Registered Date: </div></div>
<div class="col-sm-8"><?php echo $getUser->easy_date($row['created_date']);?></div>
</div>
<hr>
</div>
</div>
<div class="col-sm-3">
</div>
</div>
</div>
</body>
</html>
In the above code, we have called a fetch_user() function. The fetch_user() function will be used to get details with the user id.
Now, create the fetch_user() function inside the User class.
classes/User.php
public function fetch_user($userid)
{
$sql= "SELECT * from users WHERE id=:id";
$stmt = $this->dbConnection->prepare($sql);
$stmt->bindParam(':id', $userid, PDO::PARAM_INT);
$stmt->execute();
$row = $stmt->fetch();
return $row;
}
Kindly copy and paste this function inside the User class block of code (class {} )
Now, you can execute the login and registration form. This is a complete secure login and registration system. You can use it for a live website.
In this way, you can create login and registration forms in PHP PDO-prepared statements and OOPS concepts.
Recommended Posts:-