Pulling our resources together

Now that we have a database table, and we have our configuration file to access data from the table, we need to create a file that will pull that information together into one place. This way you can include only one file in each page that you need to acces this information from. We will create a file called common.inc.php that will include our configuration file as well as our authorization utilities file. This file will also check for the existence of an authorized user session and set a constant based on whether or not it exists.

File: common.inc.php

<?php
// Include the configuration file and Auth Utilites file
require_once('config.php');
require_once('authUtils.php');

// Start sessions
session_start();

// Check for authenticated session
if (isset($_SESSION['authenticated']) && $_SESSION['authenticated']['ip_address'] == $_SERVER['REMOTE_ADDR']) {
    define('AUTH', true);
    $auth = $_SESSION['authenticated'];
} else {
    define('AUTH', false);
    unset($_SESSION['authenticated']);
}

// function for restricting access to a page
function restrictAuth(){
   
    if (!AUTH){
        session_start();
        $_SESSION['REQUESTED'] = $_SERVER['REQUEST_URI'];
        header("location:login.php");
        exit;
    }
}

?>

First off we included our configuration and utilites files to make sure that they are available to all our scripts. We then started sessions so that we can check and access session information from within our scripts. Then we check for an authenticated session and if found define a constant and supply the information in the session to a variable for later use. Finally we define a function that we can call from any page that includes this file that will restrict access and redirect to the login page, also storing the original requested page in a session so we can redirect there after successful login.