How to create and secure a member area in PHP

The creation of an member area protected by login and password is a common request in PHP forums. In these few lines, I show you how to obtain a member area or a simple backoffice area using a login form. I only use simple PHP and session variables, so this article is accessible to beginners.

Authentication on a website is simple: the user enters his username and password in a form, then this data is compared with that which is in a database. If the two match, the user is authenticated and redirected to the correct page.

To perform authentication, we will need:

  1. To know how to use sessions in PHP.
  2. Create a users SQL table in a database called mydatabase.
  3. Create a login form: login.php.
  4. Create a backoffice or member area home page: index.php.
  5. To create a dologin.php page containing the authentication logic.

In the context of object-oriented programming, you can use an object component dedicated to authentication, or create your own component. By using suitable interfaces, you can also manage several types of connection: by form, Twitter, Google or Facebook.

Perform authentification
Attend the PHP virtual class training.

How to create and secure a member area in PHP

Firstly, let us see how to create session variables an how to ise it in PHP.

1- Sessions and session variables

Sessions allow you to create variables that cross pages. PHP has a session manager that must be activated on any page containing session variables. For each user, a session ID is created and usually stored on the client browser as a cookie. The variables associated with a session are stored on the server.

Activate a session and create variables

Here is the minimal code to activate a session, create and read session variables. The session_start() function should be at the very top, before a session variable is created:

<?php
    //Activate the PHP session manager
    session_start();
    
    //Create a session variable
    $_SESSION['lastname'] = "Dupont";
    
    //Display a session variable
    echo $_SESSION['lastname'];

?>

2- Create a SQL table : users

The users registered on your site are in a SQL users table of your MySQL database. Let's say your database is mydatabase.

We will create the SQL users table shown below,  and having 7 fields or columns.

SQL table usersid : primary key column, auto-increment.

active : lets you know if the account is active.

other fiels : of VARCHAR type. In real world, the password should not be stored in plain text in the table, but must be encrypted.

You can also guarantee the uniqueness of the login by associating a UNIQUE type constraint with this field.

To create the table, you can use the SQL code below. If you use a tool like phpMyAdmin, you can use its web interface to create the table, instead of typing SQL code.

 

CREATE TABLE users(
    id INT(3) PRIMARY KEY AUTO_INCREMENT,
    login VARCHAR(20),
    pwd VARCHAR(15),
    lastname VARCHAR(50),
    firstname VARCHAR(50),
    role VARCHAR(50),
    active TINYINT(1)
) ENGINE=InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci;

After creating your table, insert 2 users into it: one with the role of administrator, and the second that of operator. You can use the SQL code below.

INSERT INTO users
VALUES(NULL, 'admin', 'admin-pwd', 'DUPONT', 'John', 'ADMIN', 1),
(NULL, 'oper', 'oper-pwd', 'MARC', 'Lucie', 'OPERATOR', 1);

You don't have sql skills ?
Attend our SQL virtual classroom.

3- Create the login form

All the pages to be created will have the .php extension, including the login form. Indeed, it is possible to insert a PHP code, for example the message displayed when the connection fails.

Let's create the login.php page containing the login form. This form contains just HTML code, with 3 fields: a text type field for the login, a password type field for the password and a submit type field for submitting the form.

Its HTTP method is POST, and the data is submitted to the dologin.php page for processing. Note that it is still possible to process form data and authentication logic in login.php, without the need to create the dologin.php page.

An IF block allows you to test whether you have a msg parameter in the URL to display or not a message if an error occurs. This test uses the $_GET array.

<?php
    //Test
    if(isset($_GET['msg'])){
        echo "<b style='color:red;'>" . $_GET['msg'] . "</b>";
    }

?>

<form name="connection" method="post" action="dologin.php">
    Identifiant : <input type="text" name="login"><br>
    Mot de passe : <input type="password" name="pwd"><br>
    <input type="submit" name="send" value="Connection">
</form>

4- Create the authentication logic

Authentication is done according to a simple logic. The algorithm includes IF instructions and a SWITCH instruction.

Algorithme :

  • Retrieve user input.
  • Prepare the SQL query to execute in MySQL.
  • Create the connection link to MySQL.
  • Execute the query.
  • If we have a result, the authentication is OK.
    • Retrieve the data as a PHP table.
    • If the account is active
      • Depending on the role, create session variables.
      • Redirect to backoffice.
    • Otherwise, redirect to the login page.
  • Otherwise we redirect to the login page.

Notice the activation of the session manager at the beginning of the page, and the creation of session variables that can be displayed in the backoffice pages. The session variables will also be used to secure the pages according to the roles of the users.

<?php
	//Form
    if(!empty($_POST['login'])){
	
		//Activate the PHP session manager.
		session_start();
		
		//Get inputs
		$login = $_POST['login'];
		$pwd = $_POST['pwd'];
		
		//SQL code
		$query = "SELECT * FROM users WHERE login='$login' AND pwd='$pwd';";
		
		//Connection (API MySQLi)
		$db = mysqli_connect('localhost','root','','mydatabase') or die("Connection KO " . mysqli_error());
		
		//Execute the query
		$curseur = mysqli_query($db, $query) or die("exec KO " . mysqli_error());
		
		//Test : number of rows
		if(mysqli_num_rows($curseur) == 1){
			//Authentication OK, getting data
			$data = mysqli_fetch_object($curseur);
			
			//Account active or not ?
			if($data->active == 1){
				//Session variables
				$_SESSION['auth'] = $login;
				$_SESSION['lastname'] = $data->lastname;
				$_SESSION['firstname'] = $data->firstname;
				$_SESSION['active'] = $data->active;
				$_SESSION['role'] = $data->role;
				
				//Test the role
				switch($data->role){
					case 'ADMIN': header("location:" . "admin/index-admin.php");
					exit;
					break;
					
					case 'OPERATOR': header("location:" . "admin/index-operator.php");
					exit;
					break;
					
				}
			}
			else{
				//Account is active
				$msg = "Login or password incorrect.";
				
				//Redirection
				header("location:" . "login.php?msg=$msg");
				exit;
			}
		}
		else{
			//No user
			$msg = "Login or password incorrect.";
			
			//Redirection
			header("location:" . "login.php?msg=$msg");
			exit;
		}
	}
?>

5- Protect backoffice pages

Without protection, the backoffice pages can be accessed by a user who knows the URL (or who tries to guess it), without going through the login form.

To secure each backoffice page, one or more session variables can be tested. If the variable exists, then the session is active, otherwise it has expired or does not exist.

<?php
    //Test a session variable
    if(!isset($_SESSION['auth'])){
        //Error message
        $msg = "Login or password incorrect.";
        
        //Redirect
        header("location:" . "../login.php?msg=$msg");
        exit;
    }
	
	//test if the account is active
	if($_SESSION['active'] != 1){
        //Error message
        $msg = "Please contact the admin of the site.";
        
        //Redirect
        header("location:" . "../login.php?msg=$msg");
        exit;
    }
?>

Go further in PHP ?
Attend our PHP virtual classroom training.

by-titre-45845878588.png

Founder of ReCONVERT, web and e-commerce project manager, trainer of +2000 trainees face-to-face and online (LIVE and VOD). Currently, I am developing Digital Learning.

Follow me on social media.