Friday 31 January 2014

PHP Object Oriented Programming

A better programmer follows object oriented programming principals. It is deal with objects and easy to update the code. In this post I want to explain how to develop user registration and login system implementing with object oriented programming in PHP.

The tutorial contains a folder called include with PHP files.
login.php
registration.php
home.php
include
-- functions.php
-- config.php

Database
Sample database users table columns uid, username, passcode, name and email.
CREATE TABLE users
(
uid INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(30) UNIQUE,
password VARCHAR(50),
name VARCHAR(100),
email VARCHAR(70) UNIQUE
);

functions.php
Contains PHP code class User{} contains functions/methods.
<?php
include_once 'config.php';
class User
{
//Database connect 
public function __construct()
{
$db = new DB_Class();
}
//Registration process 
public function register_user($name, $username, $password, $email)
{
$password = md5($password);
$sql = mysql_query("SELECT uid from users WHERE username = '$username' or email = '$email'");
$no_rows = mysql_num_rows($sql);
if ($no_rows == 0)
{
$result = mysql_query("INSERT INTO users(username, password, name, email) values ('$username', '$password','$name','$email')") or die(mysql_error());
return $result;
}
else
{
return FALSE;
}
}
// Login process
public function check_login($emailusername, $password)
{
$password = md5($password);
$result = mysql_query("SELECT uid from users WHERE email = '$emailusername' or username='$emailusername' and password = '$password'");
$user_data = mysql_fetch_array($result);
$no_rows = mysql_num_rows($result);
if ($no_rows == 1)
{
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return TRUE;
}
else
{
return FALSE;
}
}
// Getting name
public function get_fullname($uid)
{
$result = mysql_query("SELECT name FROM users WHERE uid = $uid");
$user_data = mysql_fetch_array($result);
echo $user_data['name'];
}
// Getting session 
public function get_session()
{
return $_SESSION['login'];
}
// Logout 
public function user_logout()
{
$_SESSION['login'] = FALSE;
session_destroy();
}

}
?>

registration.php
Here $user = new User(); is the class User{} object using this calling method$user->register_user{} and inserting values.
<?php
include_once 'include/functions.php';
$user = new User();
// Checking for user logged in or not
if ($user->get_session())
{
header("location:home.php");
}

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$register = $user->register_user($_POST['name'], $_POST['username'], $_POST['password'], $_POST['email']);
if ($register)
{
// Registration Success
echo 'Registration successful <a href="login.php">Click here</a> to login';
} else
{
// Registration Failed
echo 'Registration failed. Email or Username already exits please try again';
}
}
?>
//HTML Code
<form method="POST" action="register.php" name='reg' >
Full Name
<input type="text" name="name"/>
Username
<input type="text" name="username"/>
Password
<input type="password" name="password"/>
Email
<input type="text" name="email"/>
<input type="submit" value="Register"/>
</form>

login.php
Calling method $user->check_login{} for login verification. 
<?php
session_start();
include_once 'include/functions.php';
$user = new User();
if ($user->get_session())
{
header("location:home.php");
}

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$login = $user->check_login($_POST['emailusername'], $_POST['password']);
if ($login)
{
// Login Success
header("location:login.php");
}
else
{
// Login Failed
$msg= 'Username / password wrong';
}
}
?>
//HTML Code
<form method="POST" action="" name="login">
Email or Username
<input type="text" name="emailusername"/>
Password
<input type="password" name="password"/>
<input type="submit" value="Login"/>
</form>

home.php
<?php
session_start();
include_once 'include/functions.php';
$user = new User();
$uid = $_SESSION['uid'];
if (!$user->get_session())
{
header("location:login.php");
}
if ($_GET['q'] == 'logout')
{
$user->user_logout();
header("location:login.php");
}
?>
//HTML Code
<a href="?q=logout">LOGOUT</a>
<h1> Hello <?php $user->get_fullname($uid); ?></h1>

config.php
Database configuration class DB_class() function __construct() is the method name for the constructor. 
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
class DB_Class 
{
function __construct()
{
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or
die('Oops connection error -> ' . mysql_error());
mysql_select_db(DB_DATABASE, $connection)
or die('Database error -> ' . mysql_error());
}
}
?>

How to add new function/method.
For example if you want to get email value. Just include the following function inside class User{} 
public function get_email($uid)
{
$result = mysql_query("SELECT email FROM users WHERE uid = $uid");
$user_data = mysql_fetch_array($result);
echo $user_data['email'];
}

Print email values.
<?php $user->get_email($uid); ?>

Login and Registration with OOP and PDO

Functionality

In this first part, what we are going to create is actually very simple. First we will let the user fill out a registration form. Then if the user has supplied valid information, that information will be stored in our database and an email would be send to the supplied email address with a link to activate the account. After which the user can login through a login form. If the user supplies valid username/password and if he has activated the account by clicking on the link which we had sent, he will be logged in and directed to the user's personalized home page.
Without further ado, lets get started!

Creating our Database and users table

Before we begin, make sure you have an environment setup where you can use Php and MySQL. I'll be using Xampp which is a great package. Also I'll be using phpmyAdmin as my tool for managing database, but you are free to choose your own.
Let's create a database named 'lar' for log in and registration, however, you can choose any name you want. Also, let's create a table named 'users' in that database.
Following is the image of that table that I have, also showing the database name.
database.jpg
You can see all the fields, their data types and lengths in the picture. For example, the field 'username' has the data type varchar and length 18. Also make sure that the field 'id' is autoincrement and has the index set to primary.

Folder structure and required files

Lets create the folder structure and the files (empty for now) that we are going to need, so we get an overview of what all is required.
folder_structure.jpg

Connecting to the database using PDO

Lets open our database.php file and make a connection to our database using PDO.
database.php
  1. <?php
  2. # We are storing the information in this config array that will be required to connect to the database.
  3. $config = array(
  4. 'host' => 'localhost',
  5. 'username' => 'root',
  6. 'password' => '',
  7. 'dbname' => 'lar'
  8. );
  9. #connecting to the database by supplying required parameters
  10. $db = new PDO('mysql:host=' . $config['host'] . ';dbname=' . $config['dbname'], $config['username'], $config['password']);
  11.  
  12. #Setting the error mode of our db object, which is very important for debugging.
  13. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  14. ?>
So above we have chosen mysql as our database and supplied the required information which was:
  • host - This is almost always localhost whether you are developing locally or when your site is on a web host. Localhost just means the host where the current file is located.
  • username - Username for my database is root
  • password - I have not set a password for my root user.
  • dbname - We named our database 'lar'.
Now we have created an object called $db. This object is basically a reference to our PDO class that we have instantiated by supplying our parameters. Remember PDO is a built-in class and it contains methods(which just means functions inside a class) that we are going to use to query our database.

Creating our classes in users.php and general.php

The users.php file will contain all the methods that are related to users on our website, such as registering the users, logging the user in and retrieving information about the registered user.
In a similar way general.php will contain general functions for our site.
users.php
  1. <?php
  2. class Users{
  3.  
  4. private $db;
  5.  
  6. public function __construct($database) {
  7. $this->db = $database;
  8. }
  9.  
  10. }
general.php
  1. <?php
  2. class General{
  3.  
  4.  
  5. }
We have just created our classes. We will add functions in them as we go along in the tutorial.
Since functions inside a class cannot use variables that are defined outside of it, we have used the __construct() method in our Users class to make the $db variable(or object) available in our class. This will make more sense when we will pass in the $db object that we created in our database.php in the Users class when we instantiate it.
Note: You can also make variables outside of classes available to the methods inside by making the variable global. But we are not going to cover that here, since it is not required.

Creating our init.php file

The init.php file will be included in all the files that are in our root directory which are index.php, register.php, login.php and so on, that are basically the pages that the user will access with his browser.
Below we start the user's session, include the files we just worked on and instantiate the two classes. We have also created an errors array that will help us in error handling later in the tutorial.
init.php
  1. <?php
  2. #starting the users session
  3. session_start();
  4. require 'connect/database.php';
  5. require 'classes/users.php';
  6. require 'classes/general.php';
  7.  
  8. $users = new Users($db);
  9. $general = new General();
  10.  
  11. $errors = array();
Lets take a pause and examine what we have so far. Here we have included all the neccessary files. When we include this init.php in our files in the root directory, those files will have 3 objects already created in them, which are $general, $users and $db. We created $general and $users in this file by instantiating General class and Users class that are present in general.php and users.php; whereas, $db was already created in our database.php
Now we will be able to use all the functions that we will create in our General and Users class and the built-in functions in the PDO class in all our pages.

Creating basic styling rules.

We'll start creating our pages, but first lets make some styling rules that will apply to all of them.
This is our style.css file. Just some basic style mostly to center the content, nothing pretty.
  1. @charset "utf-8";
  2.  
  3. body{
  4. font: 0.9em Tahoma, Verdana, Arial;
  5. line-height:160%;
  6. background: #ddd;
  7. }
  8.  
  9. #container{
  10. width: 1000px;
  11. padding: 25px;
  12. background: #fff;
  13. margin: 100px auto 0 auto;
  14. }
  15.  
  16. h4{
  17. margin: 0;
  18. }
  19.  
  20. ul{
  21. padding: 0;
  22. }
  23.  
  24. ul li{
  25. display: inline-block;
  26. padding: 15px;
  27. list-style: none;
  28. }

Our index page.

For the sake of this tutorial I have only put a welcome message and navigation that contains links to the index.php, login.php and register.php. The rest of the pages will use the same basic markup.
index.php
  1. <?php
  2. #including our init.php
  3. require 'core/init.php';
  4. ?>
  5. <!doctype html>
  6. <html lang="en">
  7. <head>
  8. <meta charset="UTF-8">
  9. <link rel="stylesheet" type="text/css" href="css/style.css" >
  10. <title>Login and registration</title>
  11. </head>
  12. <body>
  13. <div id="container">
  14. <ul>
  15. <li><a href="index.php">Home</a></li>
  16. <li><a href="register.php">Register</a></li>
  17. <li><a href="login.php">Login</a></li>
  18. </ul>
  19. <h1>Welcome to our site!</h1>
  20. </div>
  21. </body>
  22. </html>
Make sure you include the init.php file in all the pages. We have done it with the require function.
With the style sheet included, your index.php file should look like this:

Now as we go along, we are going to create our pages that the user is going to view and add functions in our classes accordingly.

Registering the user.

Following is the register.php file that contains a form, that when submitted sends data with the method of POST to register.php itself. At the top of the file is all the logic that shows what happens when $_POST is set, which means when the form is submitted. The logic includes verifying the data, checking for errors and registering the users in case of no errors.
register.php
  1. <?php
  2. require 'core/init.php';
  3.  
  4. # if form is submitted
  5. if (isset($_POST['submit'])) {
  6.  
  7. if(empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email'])){
  8.  
  9. $errors[] = 'All fields are required.';
  10.  
  11. }else{
  12. #validating user's input with functions that we will create next
  13. if ($users->user_exists($_POST['username']) === true) {
  14. $errors[] = 'That username already exists';
  15. }
  16. if(!ctype_alnum($_POST['username'])){
  17. $errors[] = 'Please enter a username with only alphabets and numbers';
  18. }
  19. if (strlen($_POST['password']) <6){
  20. $errors[] = 'Your password must be at least 6 characters';
  21. } else if (strlen($_POST['password']) >18){
  22. $errors[] = 'Your password cannot be more than 18 characters long';
  23. }
  24. if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
  25. $errors[] = 'Please enter a valid email address';
  26. }else if ($users->email_exists($_POST['email']) === true) {
  27. $errors[] = 'That email already exists.';
  28. }
  29. }
  30.  
  31. if(empty($errors) === true){
  32. $username = htmlentities($_POST['username']);
  33. $password = $_POST['password'];
  34. $email = htmlentities($_POST['email']);
  35.  
  36. $users->register($username, $password, $email);// Calling the register function, which we will create soon.
  37. header('Location: register.php?success');
  38. exit();
  39. }
  40. }
  41.  
  42. if (isset($_GET['success']) && empty($_GET['success'])) {
  43. echo 'Thank you for registering. Please check your email.';
  44. }
  45. ?>
  46. <!doctype html>
  47. <html lang="en">
  48. <head>
  49. <meta charset="UTF-8">
  50. <link rel="stylesheet" type="text/css" href="css/style.css" >
  51. <title>Register</title>
  52. </head>
  53. <body>
  54. <div id="container">
  55. <ul>
  56. <li><a href="index.php">Home</a></li>
  57. <li><a href="register.php">Register</a></li>
  58. <li><a href="login.php">Login</a></li>
  59. </ul>
  60. <h1>Register</h1>
  61.  
  62. <form method="post" action="">
  63. <h4>Username:</h4>
  64. <input type="text" name="username" />
  65. <h4>Password:</h4>
  66. <input type="password" name="password" />
  67. <h4>Email:</h4>
  68. <input type="text" name="email" />
  69. <br>
  70. <input type="submit" name="submit" />
  71. </form>
  72.  
  73.  
  74. <?php
  75. # if there are errors, they would be displayed here.
  76. if(empty($errors) === false){
  77. echo '<p>' . implode('</p><p>', $errors) . '</p>';
  78. }
  79.  
  80. ?>
  81.  
  82. </div>
  83. </body>
  84. </html>
Above we used 3 functions (user_exists, email_exists and register) that we will create next. We also used the built-in strlen and filter_var to make other validations.
Take note that the errors array is the array that we defined in our init.php which is included at the top.
Lets create our user_exists method, email_exists method and our register() method inside our Users class.
Add this in the Users class in users.php
  1. <?php
  2.  
  3. public function user_exists($username) {
  4.  
  5. $query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?");
  6. $query->bindValue(1, $username);
  7.  
  8. try{
  9.  
  10. $query->execute();
  11. $rows = $query->fetchColumn();
  12.  
  13. if($rows == 1){
  14. return true;
  15. }else{
  16. return false;
  17. }
  18.  
  19. } catch (PDOException $e){
  20. die($e->getMessage());
  21. }
  22.  
  23. }
  24. public function email_exists($email) {
  25.  
  26. $query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email`= ?");
  27. $query->bindValue(1, $email);
  28.  
  29. try{
  30.  
  31. $query->execute();
  32. $rows = $query->fetchColumn();
  33.  
  34. if($rows == 1){
  35. return true;
  36. }else{
  37. return false;
  38. }
  39.  
  40. } catch (PDOException $e){
  41. die($e->getMessage());
  42. }
  43.  
  44. }
  45.  
  46. public function register($username, $password, $email){
  47. $time = time();
  48. $ip = $_SERVER['REMOTE_ADDR'];
  49. $email_code = sha1($username + microtime());
  50. $password = sha1($password);
  51.  
  52. $query = $this->db->prepare("INSERT INTO `users` (`username`, `password`, `email`, `ip`, `time`, `email_code`) VALUES (?, ?, ?, ?, ?, ?) ");
  53.  
  54. $query->bindValue(1, $username);
  55. $query->bindValue(2, $password);
  56. $query->bindValue(3, $email);
  57. $query->bindValue(4, $ip);
  58. $query->bindValue(5, $time);
  59. $query->bindValue(6, $email_code);
  60.  
  61. try{
  62. $query->execute();
  63.  
  64. // mail($email, 'Please activate your account', "Hello " . $username. ",\r\nThank you for registering with us. Please visit the link below so we can activate your account:\r\n\r\nhttp://www.example.com/activate.php?email=" . $email . "&email_code=" . $email_code . "\r\n\r\n-- Example team");
  65. }catch(PDOException $e){
  66. die($e->getMessage());
  67. }
  68. }
Now this is where you need to have some knowledge of PDO and OOP. Basically in all the above methods we are using the $db object which we defined in our __construct method (remember we are in users.php). In all our methods, first we prepare a statement and put a '?' where we would have user defined variables such as $username and $email. Then we bind those variables into their respective places using the PDO method bindValue. You can see how this way we can tell PDO which ones are query statements and which ones are user defined variables. And PDO does the job of automatically cleaning those variables of any SQL injection.
Warning: To keep things simple, I used the sha1() function for hashing passwords, but it is not the safest method available. The best in my opinion is using the BLOWFISH bcrypt(). We will cover that in the next part of this series.
After we have prepared the query and bind values to it, we execute it. And then get the desired result.
Also, notice that the execute function is in a try block. So if there is some error or if we have made a mistake, the try block will fail and a PDO Exception will be caught. Using try and catch blocks will give us a specific and useful indication of the problem.
Note: We used the mail function to send the email to the user. But it will usually only work when you put your website on a web host. Sending email when developing on localhost can be tricky. So if you are developing locally I suggest that you comment out the mail function for now and remove those comments only when you make your site live.

Activating the user's account

So far we have successfully registered the users information in our database, and emailed him a link to our activate.php file with the email and the randomly generated email_code as parameters. We also stored that generated email_code in our database when we registered the user. So when a user visits activate.php with email and email_code in the url, we can check the email and email_code in the url and compare the values in our database.
activate.php
  1. <?php
  2. require 'core/init.php';
  3. ?>
  4. <!doctype html>
  5. <html lang="en">
  6. <head>
  7. <meta charset="UTF-8">
  8. <link rel="stylesheet" type="text/css" href="css/style.css" >
  9. <title>Activate</title>
  10. </head>
  11. <body>
  12. <div id="container">
  13. <ul>
  14. <li><a href="index.php">Home</a></li>
  15. <li><a href="register.php">Register</a></li>
  16. <li><a href="login.php">Login</a></li>
  17. </ul>
  18. <h1>Activate your account</h1>
  19.  
  20. <?php
  21. if (isset($_GET['success']) === true && empty ($_GET['success']) === true) {
  22. ?>
  23. <h3>Thank you, we've activated your account. You're free to log in!</h3>
  24. <?php
  25. } else if (isset ($_GET['email'], $_GET['email_code']) === true) {
  26. $email =trim($_GET['email']);
  27. $email_code =trim($_GET['email_code']);
  28. if ($users->email_exists($email) === false) {
  29. $errors[] = 'Sorry, we couldn\'t find that email address.';
  30. } else if ($users->activate($email, $email_code) === false) {
  31. $errors[] = 'Sorry, we couldn\'t activate your account.';
  32. }
  33. if(empty($errors) === false){
  34. echo '<p>' . implode('</p><p>', $errors) . '</p>';
  35. } else {
  36.  
  37. header('Location: activate.php?success');
  38. exit();
  39.  
  40. }
  41. } else {
  42. header('Location: index.php');
  43. exit();
  44. }
  45. ?>
  46. </div>
  47. </body>
  48. </html>
The only thing new in this is the activate function that is called to check whether the supplied email/email_code matches any email/email_code in our database. Below we create that function inside our Users Class.
Add this in Users class in users.php
  1. <?php
  2. public function activate($email, $email_code) {
  3. $query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email` = ? AND `email_code` = ? AND `confirmed` = ?");
  4.  
  5. $query->bindValue(1, $email);
  6. $query->bindValue(2, $email_code);
  7. $query->bindValue(3, 0);
  8.  
  9. try{
  10.  
  11. $query->execute();
  12. $rows = $query->fetchColumn();
  13.  
  14. if($rows == 1){
  15. $query_2 = $this->db->prepare("UPDATE `users` SET `confirmed` = ? WHERE `email` = ?");
  16.  
  17. $query_2->bindValue(1, 1);
  18. $query_2->bindValue(2, $email);
  19.  
  20. $query_2->execute();
  21. return true;
  22.  
  23. }else{
  24. return false;
  25. }
  26.  
  27. } catch(PDOException $e){
  28. die($e->getMessage());
  29. }
  30. }
In the activate function, we take in the $email and $email_code as parameters into our function. In our first query we check if we have a row in our database that has the supplied email and the email_code. If there is such a row, then we do another query in which we update the 'confirmed' field in that row and set it to 1 from the default 0.

Logging the user in

Logging the user consists of setting something in the $_SESSION variable. Notice that we use session_start() at the start of every page, since that is top most thing in our init.php. So in login.php, all we have to do is take the user's username and password and validate it. If the user supplies the correct username/password combination, then we will set the id corresponding to that username to a $_SESSION variable. By setting the id as a variable in the session, we can know that the session is that of a logged in user and also who the user is.
First let's create the login method in our Users class, which we are going to uses shortly in our login.php
Add this in Users class in users.php
  1. <?php
  2.  
  3. public function login($username, $password) {
  4.  
  5. $query = $this->db->prepare("SELECT `password`, `id` FROM `users` WHERE `username` = ?");
  6. $query->bindValue(1, $username);
  7. try{
  8. $query->execute();
  9. $data = $query->fetch();
  10. $stored_password = $data['password'];
  11. $id = $data['id'];
  12. #hashing the supplied password and comparing it with the stored hashed password.
  13. if($stored_password === sha1($password)){
  14. return $id;
  15. }else{
  16. return false;
  17. }
  18.  
  19. }catch(PDOException $e){
  20. die($e->getMessage());
  21. }
  22. }
So in this function we take in the username and the password. The query selects the password and id for that username. Further down we check if the sha1 hash of the supplied password is equal to the stored password, which was also hashed using the same sha1 hashing method. If they are equal then we return the selected id otherwise we return false.
Before we login the user, we will also need to check if the user has activated his account, so we need to create another function in our Users class.
Add this in Users class in users.php
  1. <?php
  2. public function email_confirmed($username) {
  3.  
  4. $query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ? AND `confirmed` = ?");
  5. $query->bindValue(1, $username);
  6. $query->bindValue(2, 1);
  7. try{
  8. $query->execute();
  9. $rows = $query->fetchColumn();
  10.  
  11. if($rows == 1){
  12. return true;
  13. }else{
  14. return false;
  15. }
  16.  
  17. } catch(PDOException $e){
  18. die($e->getMessage());
  19. }
  20.  
  21. }
  22. ?>
In the above function, we only check if the supplied username has the 'confirmed' field in the 'users' table set to 1 or not. If it is 1 we return true otherwise we return false.
Now we will create our login.php and use the two function we just created.
login.php
  1. <?php
  2. require 'core/init.php';
  3.  
  4. if (empty($_POST) === false) {
  5.  
  6. $username = trim($_POST['username']);
  7. $password = trim($_POST['password']);
  8.  
  9. if (empty($username) === true || empty($password) === true) {
  10. $errors[] = 'Sorry, but we need your username and password.';
  11. } else if ($users->user_exists($username) === false) {
  12. $errors[] = 'Sorry that username doesn\'t exists.';
  13. } else if ($users->email_confirmed($username) === false) {
  14. $errors[] = 'Sorry, but you need to activate your account.
  15. Please check your email.';
  16. } else {
  17.  
  18. $login = $users->login($username, $password);
  19. if ($login === false) {
  20. $errors[] = 'Sorry, that username/password is invalid';
  21. }else {
  22. // username/password is correct and the login method of the $users object returns the user's id, which is stored in $login.
  23.  
  24. $_SESSION['id'] = $login; // The user's id is now set into the user's session in the form of $_SESSION['id']
  25. #Redirect the user to home.php.
  26. header('Location: home.php');
  27. exit();
  28. }
  29. }
  30. }
  31. ?>
  32. <!doctype html>
  33. <html lang="en">
  34. <head>
  35. <meta charset="UTF-8">
  36. <link rel="stylesheet" type="text/css" href="css/style.css" >
  37. <title>Login</title>
  38. </head>
  39. <body>
  40. <div id="container">
  41. <ul>
  42. <li><a href="index.php">Home</a></li>
  43. <li><a href="register.php">Register</a></li>
  44. <li><a href="login.php">Login</a></li>
  45. </ul>
  46. <h1>Login</h1>
  47.  
  48. <?php if(empty($errors) === false){
  49.  
  50. echo '<p>' . implode('</p><p>', $errors) . '</p>';
  51.  
  52. }
  53. ?>
  54. <form method="post" action="">
  55. <h4>Username:</h4>
  56. <input type="text" name="username">
  57. <h4>Password:</h4>
  58. <input type="password" name="password">
  59. <br>
  60. <input type="submit" name="submit">
  61. </form>
  62. </div>
  63. </body>
  64. </html>
The login.php is similar to register.php. We have a form where we take the username and password. We make regular checks at the top such as whether the username exists or whether the user has confirmed his account. If these tests fail, errors regarding that test are added to the errors array. Which is then displayed above the form.
If all the tests succeed and if there are no errors, then we call the login function using our $users object. If the supplied username/password is incorrect the login function will return false and appropriate error will be displayed. However, if the username/password is correct, then the user's id will be set in the $_SESSION variable and the user will be directed to the home.php page.

Homepage for the user after login.

So this is similar to what happens when you login to Facebook, which is after you have logged in you are directed to your Facebook homepage where you have your personalized data displayed such as your News feed, your friend list and other things. We however, will only display the user's personal username :)
After the user has logged in, we have the user's id stored in the session. So we can use that to get all the data we need from our table for this id. We create yet another function in our Users class to get user's information using the user's id.
Add this in Users class in users.php
  1. <?php
  2. public function userdata($id) {
  3.  
  4. $query = $this->db->prepare("SELECT * FROM `users` WHERE `id`= ?");
  5. $query->bindValue(1, $id);
  6.  
  7. try{
  8.  
  9. $query->execute();
  10.  
  11. return $query->fetch();
  12.  
  13. } catch(PDOException $e){
  14.  
  15. die($e->getMessage());
  16. }
  17. }
The above function will return the user's data in the form of an array.
Over to our home.php file
  1. <?php
  2. require 'core/init.php';
  3.  
  4. $user = $users->userdata($_SESSION['id']);
  5. $username = $user['username'];
  6.  
  7. ?>
  8. <!doctype html>
  9. <html lang="en">
  10. <head>
  11. <meta charset="UTF-8">
  12. <link rel="stylesheet" type="text/css" href="css/style.css" >
  13. <title>Home</title>
  14. </head>
  15. <body>
  16. <div id="container">
  17. <ul>
  18.  
  19. <li><a href="index.php">Home</a></li>
  20. <li><a href="logout.php">Logout</a></li>
  21.  
  22. </ul>
  23. <h1>Hello <?php echo $username, '!'; ?></h1><!-- This will say Hello sunny! for example -->
  24. </div>
  25. </body>
  26. </html>
We call the userdata() method of the $users object and store the 'username' index in the variable $username, and echo out 'Hello sunny!'(for example). Also notice the navigation has link to home.php and also logout.php which we will create next.

Logging the user out

logout.php
  1. <?php
  2. session_start();
  3. session_destroy();
  4. header('Location:index.php');
  5. ?>
This is it. This will successfully destroy the user's session and redirect him/her to index.php

Restricting access to users

You might be wondering that we created the our $general object and its corresponding class General, but we never used it. We will create the following functions in the General class.
Add this in the General class in general.php
  1. <?php
  2. #Check if the user is logged in.
  3. public function logged_in () {
  4. return(isset($_SESSION['id'])) ? true : false;
  5. }
  6.  
  7. #if logged in then redirect to home.php
  8. public function logged_in_protect() {
  9. if ($this->logged_in() === true) {
  10. header('Location: home.php');
  11. exit();
  12. }
  13. }
  14. #if not logged in then redirect to index.php
  15. public function logged_out_protect() {
  16. if ($this->logged_in() === false) {
  17. header('Location: index.php');
  18. exit();
  19. }
  20. }
Note: Inside logged_in_protect() and logged_out_protect() we use the $this operator to call the function $logged_in() because that function is in the same class as the two functions. Just like in our Users class we used $this operator to use the $db parameter(variable) that was defined inside that class.
The reason we created the last two functions is to restrict access to pages from users that should not see them. For example we don't want a logged in user to be able to visit register.php or login.php. In the same way we don't want users that are not logged in to visit home.php
So you need to put logged_in_protect() and logged_out_protect() at the top of different pages accordingly.
For example, we will call the logged_in_protect() function at the top of login.php right after we include init.php. Like this:
login.php
  1. <?php
  2. require 'core/init.php';
  3. $general->logged_in_protect();
  4. ?>
  5. <!--
  6. .
  7. .
  8. .
  9. Rest of the login.php
  10. .
  11. .
  12. .
  13. -->
Similarly we will call logged_out_protect() at the top of home.php
home.php
  1. <?php
  2. require 'core/init.php';
  3. $general->logged_out_protect();
  4. ?>
  5. <!--
  6. .
  7. .
  8. .
  9. Rest of the home.php
  10. .
  11. .
  12. .
  13. -->
Along with login.php, you need to call logged_in_protect() at the top of register.php, activate.php and index.php
Because our application only has one page(home.php) that is exclusive for a logged in user, we only need to call logged_out_protect() at the top of home.php.

Creating the list of the registered users

Lets wrap up and create our members.php file, where we list all the registered users. For this we will create our final function of the tutorial, which will go in our Users class.
For the last time add this in Users class in users.php
  1. <?php
  2.  
  3. public function get_users() {
  4.  
  5. #preparing a statement that will select all the registered users, with the most recent ones first.
  6. $query = $this->db->prepare("SELECT * FROM `users` ORDER BY `time` DESC");
  7. try{
  8. $query->execute();
  9. }catch(PDOException $e){
  10. die($e->getMessage());
  11. }
  12.  
  13. # We use fetchAll() instead of fetch() to get an array of all the selected records.
  14. return $query->fetchAll();
  15. }
  16. ?>
members.php
  1. <?php
  2. require 'core/init.php';
  3.  
  4. $members = $users->get_users();
  5. $member_count = count($members);
  6. ?>
  7.  
  8. <!doctype html>
  9. <html lang="en">
  10. <head>
  11. <meta charset="UTF-8">
  12. <link rel="stylesheet" type="text/css" href="css/style.css" >
  13. <title>Members</title>
  14. </head>
  15. <body>
  16. <div id="container">
  17. <h1>Our members</h1>
  18. <p>We have a total of <strong><?php echo $member_count; ?></strong> registered users.</p>
  19.  
  20. <?php
  21. #Showing the username and the date of joining, using the date() function.
  22. foreach ($members as $member) {
  23. echo '<p>',$member['username'], ' joined: ', date('F j, Y', $member['time']), '</p>';
  24. }
  25. ?>
  26. </div>
  27. </body>
  28. </html>

Conclusion

Since the purpose of this tutorial was to create a practical example of an application using OOP and PDO together and to keep the tutorial as short as possible, I did not cover few things:
  • Denying access to your core folder, so people cannot access it from their browsers. You can easily do that using a htaccess file.
  • In our login.php and register.php each time there is an error, the user will have to re-enter everything again in the form. This can be frustrating, what you can do is when the page refreshes with an error you can echo out the value stored in $_POST as values of the input fields accordingly, but make sure you clean them by using the Php's htmlentities function before echoing them out.
  • We also missed out an important feature of having a 'forgot your password' functionality. You can most simply do this by generating a random password and emailing that to the user, when a user asks for it.