PHP Login and Registration Script with PDO and OOP

In our previous tutorial, we learned about Registration system using Php and MySQL If you haven’t checked it our I suggest You go through the tutorial as well.
In this tutorial, we will learn about log-in and registration of users using Object-Oriented PHP as well as PDO to access database.

Overview

During the whole tutorial, You will need the following pages. You need to insert the codes below in each of the files, group them in the same folder and save them.
Specific purposes of each of the files and its codes will be discussed in later part of the guide.

  • CRUD.php
  • dbConnect.php
  • home.php
  • index.php
  • logout.php
  • signup.php

CRUD.php

Crude is a PHP file, that contains all the Server-Side code written against the Database, in order to perform the CRUD operations. This file uses PHP built-in PDO library in order to interact with the database.
All the CRUD operations which are more relevant to application logic is written here and when needed an Object of this class can be called/used to perform required activities.

<?php

class CRUD {

private $Db;

function __construct($DB_CON)
{
$this->Db = $DB_CON;
}

public function createUser($username,$email,$password){

try{

$statement = $this->Db->prepare("INSERT INTO users(username,email,password) VALUES (:uname,:mail,:pass)");
$statement->bindparam(":uname",$username);
$statement->bindparam(":mail",$email);
$statement->bindparam(":pass",$password);

$statement->execute();

return true;

} catch (PDOException $ex){
echo $ex->getMessage();
return false;
}
}

public function getUser($email){

try{

$statement = $this->Db->prepare("SELECT * FROM users WHERE email=:mail");
$statement->execute(array(":mail"=>$email));
$dataRows = $statement->fetch(PDO::FETCH_ASSOC);

return $dataRows;

} catch (PDOException $ex){
echo $ex->getMessage();
}
}
}

Database connection(dbConnect.php)

In short, the file contains the code which establishes the connection with the database.

“'mysql:host=localhost;dbname=userdb',$DB_USER,$DB_PASS”

is used as the connection string.

<?php

$DB_HOST = 'localhost';
$DB_USER = 'user';
$DB_PASS = "123456";
$DB_NAME = 'userdb';

try {

$DB_CON = new PDO('mysql:host=localhost;dbname=userdb',$DB_USER,$DB_PASS);
$DB_CON->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $ex){

echo $ex->getMessage();

}

include_once 'CRUD.php';
$crud = new CRUD($DB_CON);

Home.php

This File contains the HTML view which is rendered as soon as the user logs in the system successfully. It also contains the necessary validation codes to check if a user has a valid session.

<?php

session_start();
include_once 'dbConnect.php';

if(!isset($_SESSION['user']))
{
header("Location: index.php");
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome - <?php echo $_SESSION['user']; ?></title>
</head>
<body>
<div id="header">

<div id="right">
<div id="content">
hi' <?php echo $_SESSION['user']; ?>&nbsp;<a href="logout.php?logout">Sign Out</a>
</div>
</div>
</div>
</body>
</html>

Index.php

The index file contains the code which renders the HTML view for the user to log in as well as the Server-side code that is used to validate and log in a valid user.
The file embeds the codes that assign and also in user with a valid session.

<?php
session_start();

include_once 'dbConnect.php';

if (isset($_SESSION['user']) != "") {
header("Location: home.php");
}
if (isset($_POST['login_btn'])) {
$email = $_POST['email'];
$password = $_POST['password'];

$row = $crud->getUser($email);

if ($row['password'] == $password) {
$_SESSION['user'] = $row['username'];
header("Location: home.php");
} else {
echo("Wrong Credentials");
}

}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Tutorial - 07</title>
</head>
<body>
<center>
<div>
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="email" placeholder="Your Email" required/></td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Your Password" required/></td>
</tr>
<tr>
<td>
<button type="submit" name="login_btn">Sign In</button>
</td>
</tr>
<tr>
<td><a href="signup.php">Sign Up</a></td>
</tr>
</table>
</form>
</div>
</center>
</body>
</html>

Logout.php

Logout page contains the code which destroys a valid session. It contains the code to validate the user request in order to prevent direct URL navigation.

<?php
session_start();

if(!isset($_SESSION['user']))
{
header("Location: index.php");
}
else if(isset($_SESSION['user'])!="")
{
header("Location: home.php");
}

if(isset($_GET['logout']))
{
session_destroy();
unset($_SESSION['user']);
header("Location: index.php");
}

?>

Signup.php

Signup is a PHP file that contains the code used to register a user. It also contains the code to render HTML form to input user data as well as the Server-side code which is used against the database transaction file CRUD.php to perform the Create user function.

<?php
session_start();
if(isset($_SESSION['user']) != ""){
header("Location: home.php");
}

include_once 'dbConnect.php';

if(isset($_POST['signup_btn'])) {
$username = $_POST['usrname'];
$email = $_POST['email'];
$password = $_POST['password'];

if($crud->createUser($username,$email,$password)){
echo("Registration Successful");
}
else{
echo("Registration Failed");
}

}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Tutorial - 07</title>
</head>
<body>
<center>
<div>
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="usrname" placeholder="UserName" required /></td>
</tr>
<tr>
<td><input type="email" name="email" placeholder="Your_Email" required /></td>
</tr>
<tr>
<td><input type="password" name="password" placeholder="Your_Password" required /></td>
</tr>
<tr>
<td><button type="submit" name="signup_btn">Sign Up</button></td>
</tr>
<tr>
<td><a href="index.php">Sign In</a></td>
</tr>
</table>
</form>
</div>
</center>
</body>
</html>

Download the complete source code and a working demo.

Download the complete source code.

Grab the the free working demo Intantly!

You have Successfully Suscribed!

9 thoughts on “PHP Login and Registration Script with PDO and OOP

  1. Don’t try this!!! This has no security. It doesn’t validate all the possible form input. It’s vulnerable to XSS, SQLI… I can do better than that.

    1. Dear BenJunior,
      I appreciate your effort on viewing my site. I would love to see you improving upon the tutorials and helping the community. If you want to help improving the codes please contact me. I and the community would really appreciate.

      Regards.

  2. Muchas Gracias, solo un comentario, creo el código tiene un error, en index.php, linea 14, debería ser ‘usrname’ y no ‘username’, ya que así se maneja la conexión con la base de datos. Saludos!

  3. Hi, I was looking for a relative simple login script (so I don’t have to invent yet another wheel). When I was looking at the code I got the strong impression it was not good enough. BENJUNIOR has a point. You should add some code to verify the user input (never trust a user). Illegal input could ruin your database or get illegal access.
    You don’t use any form of encryption, so all information is send over the internet in a human readable form. For passwords this is “Not Done”. You don’t need the real password anyway, just store the encrypted version.
    If someone wants to use this code, It is simple and it works, but do take some extra time to make it more save.

  4. It is really a nice and helpful piece of info.
    I’m glad that you simply shared this useful info with us.
    Please stay us informed like this. Thanks for sharing.

  5. I believe what you published was actually very logical.

    However, what about this? what if you were
    to create a killer post title? I ain’t saying your information is not
    good, but what if you added a title to maybe grab folk’s attention? I mean PHP Login and Registration Script with PDO and OOP |
    All About PHP is kinda boring. You should peek at Yahoo’s front page and see how they create
    article headlines to grab people interested. You might add
    a video or a pic or two to grab readers interested about what you’ve got to say.
    Just my opinion, it might bring your posts a little bit more interesting.

Leave a Reply

Your email address will not be published. Required fields are marked *