RabbitLite Framework v1: Documentation

1. Overview

RabbitLite v1 is a lightweight framework designed to accelerate PHP application development for the web. It provides modular functionality, centralized configuration, and reusable components, enabling developers to build structured, scalable, and maintainable web applications.

This documentation covers framework components, deployment steps, a sample application setup, and general recommendations for using RabbitLite.

2. File Structure (Example: `school_fees` project)

The following is an example file structure, derived from the path.md, illustrating how RabbitLite components might be organized in a project like `school_fees` located at c:\xamppserv\htdocs\school_fees\.

Core Application Files:

  • index.php: Main entry point. Initializes sessions, includes core files.
  • control/global.php: Global configuration. Initializes variables, loads classes, sets up DB.
  • control/functions.php: Global helper functions (Markdown, validation, path retrieval). Includes _doc/index.php or control/route.php.
  • control/navgation.php: The primary router/dispatcher. Determines logic based on $_REQUEST parameters (submit, page, main).
  • control/connection.php: Handles database connections (SQLite, MySQL, MS Access) via PDO.
  • control/control.php: Contains the control class for file management utilities.

Route Files:

  • control/route.php: Fallback routing. Handles requests if _doc folder is not present/empty. Included by functions.php.
  • control/route/main.php: Handles requests for specific "main" sections. Included by navgation.php.
  • control/route/page.php: Handles requests for specific "pages". Included by navgation.php.
  • control/route/action.php: Handles form submissions or actions. Included by navgation.php when submit is set. (Note: This might be a specific implementation detail, as there's also a root action.php, which is more typical for handling `$_REQUEST['submit']`).

Documentation Files (_doc/ directory):

  • _doc/index.php: Main documentation page, displays Markdown help files. Included by functions.php if _doc exists.
  • _doc/*.md: Various Markdown files (help.md, index.md, global.md, controller.md, database.md, functions.md, navgation.md, action.md) containing detailed documentation for components.

Template Files:

  • templates/login.php: Example login template, often the default page.
  • templates/*: Other application-specific view templates.

Assets Files:

  • assets/css/bootstrap.min.css
  • assets/font/bootstrap-icons.css
  • assets/js/bootstrap.bundle.min.js

Models Files:

  • models/*: Contains all data models or business logic classes.

3. Framework Components

RabbitLite is composed of several core PHP files, each serving a specific purpose to create a modular and manageable application structure.

3.1 index.php (Application Entry Point)

The index.php file acts as the primary entry point for your PHP application. It initializes essential components, manages session functionality, and loads required resources.

Core Logic:

  1. Starting a Session:
    session_start(); // Start a new session

    Initializes a session for tracking user data across requests, enabling features like authentication and state persistence.

  2. Including Required Files:
    require_once("./control/control.php");
    require_once("./control/functions.php");
    require_once("./control/global.php");
    require_once("./control/route.php"); // Or navgation.php depending on setup
    // Potentially other core includes like navgation.php if not in global.php
                                    

    Ensures necessary files are loaded. The route.php (or navgation.php) handles dynamic content loading or actions.

Summary of Typically Included Files:

FilePurpose
control/control.phpUtility methods for file management.
control/functions.phpGlobal helper functions (Markdown parsing, validation).
control/global.phpGlobal configuration (DB settings, paths).
control/navgation.php or control/route.phpRouting logic.

Recommendations for index.php:

  • Session Security: Implement robust session security measures (e.g., configure cookie lifetime, use read_and_close if applicable).
  • Error Handling: Add checks for file existence before requiring them to prevent fatal errors.

3.2 global.php (Global Configuration)

The global.php file serves as a centralized configuration and initialization script. It loads dependencies, initializes core components, and defines global variables.

Key Operations:

  1. Loading Files:
    // Assumes $controller is an instance of the 'control' class
    $models = $controller->requireAllPhpFiles('./models');
    $temp = $controller->getAllPhpFilesTemplate('./templates'); // templates available as an array
    $functions = $controller->requireAllAutoloadFiles('./modal/composer'); // For Composer's autoload
                                    

    Uses the control class methods to load models, template paths, and Composer dependencies.

  2. Database Configuration:
    Database::$dbType = 'sqlite';
    Database::$dbName = 'lms.db';
    Database::$dbPath = './data/'; // Path for SQLite/Access files
                                    

    Sets static properties for the Database class (see connection.php).

  3. Initializing Libraries:
    $parsedown = new Parsedown(); // For Markdown to HTML
    $jsql = new JsonDataManager('data/data.json'); // Example for JSON data management
                                    
  4. Main Page & Action Configuration:
    // $_MAIN_PAGE_PATH usually set in navgation.php or based on routing logic
    // Example: if $temp['login'] exists, it might be:
    // $_MAIN_PAGE_PATH = $temp['login'] ?? 'templates/default.php';
    $_PAGE_ACTION = ''; // Placeholder for current page action
                                    
  5. Application Labels:
    $lable = [
        "title" => "My Application", // Corrected typo from "tilte"
        "application" => "RabbitLite Powered App",
        "version" => "1.0.0",
    ];
                                    

Recommendations for global.php:

  • Error Handling: Check return values from file loading methods.
  • Clarity: Ensure paths are correct and well-documented.
  • Security: Avoid hardcoding sensitive credentials if possible; use environment variables for production.

3.3 control.php (File Management Utilities)

The control class in control.php provides utility functions for managing PHP files and dependencies, such as dynamic retrieval and inclusion.

Class Methods:

MethodParametersReturn TypeDescription
getAllPhpFiles()$directory (string)array|stringRetrieves all .php file paths from directory and subdirectories.
getAllPhpFilesTemplate()$directory (string)array|stringRetrieves .php file paths as key (filename w/o ext) - value (path) pairs.
requireAllPhpFiles()$directory (string)array|stringIncludes all .php files from the specified directory using require_once.
requireAllAutoloadFiles()$directory (string)array|stringIncludes all autoload.php files from the specified directory.

Example Usage:

$controller = new control();

// Retrieve all PHP files from './models'
$phpFiles = $controller->getAllPhpFiles('./models');
if (is_array($phpFiles)) {
    print_r($phpFiles);
} else {
    echo $phpFiles; // Error message
}

// Retrieve template paths
$templates = $controller->getAllPhpFilesTemplate('./templates');
// $templates['login'] would give path to 'login.php'

// Include all PHP files from './models'
$includedFiles = $controller->requireAllPhpFiles('./models');
                        

Recommendations for control.php:

  • Error Handling: Methods should return clear error messages or throw exceptions for invalid directories or file issues. The current array|string return type requires careful checking by the caller.
  • Performance: For frequently called methods, consider caching results.
  • Security: Sanitize directory paths if they can be influenced by user input, though typically these are hardcoded.

3.4 functions.php (Global Utility Functions)

The functions.php file provides a collection of global utility functions.

Functions Breakdown:

loadMarkdownContent($markdownFile)

Converts Markdown content from a file into HTML using a global Parsedown instance.

Returns: HTML string or error message if file not found.

$htmlContent = loadMarkdownContent('_doc/help.md');
echo $htmlContent;
getCurrentScriptPath()

Retrieves and sanitizes the path of the currently executing PHP script.

Returns: Sanitized script path string.

validateUrlRegex($url)

Validates a URL using a regular expression.

Returns: true if valid, false otherwise.

validateEmailBasic($email)

Validates an email address using filter_var().

Returns: true if valid, false otherwise.

getDocOrRoutePath() (Implied)

This function is mentioned in path.md as part of functions.php's role. It likely determines whether to include documentation (_doc/index.php) or the main application routing (control/route.php) based on the existence of the _doc folder.

// Conceptual logic within functions.php
if (is_dir('_doc') && !empty(glob('_doc/*.md'))) { // Check if _doc exists and has markdown
    require_once('_doc/index.php');
} else {
    require_once('control/route.php'); // Fallback or main app routing
}

Recommendations for functions.php:

  • Error Handling: Provide more descriptive error messages.
  • Input Sanitization: Ensure inputs are sanitized where appropriate, especially if they originate from users.
  • Modularity: Keep functions focused on a single task.

3.5 connection.php (Database Class)

The Database class in connection.php manages database connections, supporting SQLite, MySQL, and Microsoft Access.

Class Properties (Static):

  • $pdo (private): Stores the PDO connection object.
  • $dbName: Name of the database.
  • $dbPath (default 'data/'): Directory for SQLite/Access files.
  • $dbHost, $dbUser, $dbPass: MySQL credentials.
  • $dbType: 'sqlite', 'mysql', or 'access'.
  • $dbExtension (default '.db'): For SQLite.

Key Methods:

connect(): PDO|string
Establishes a DB connection based on $dbType. Returns PDO object or error string.
closeConnection(): void
Sets $pdo to null to close the connection.

Example Usage (SQLite):

Database::$dbType = 'sqlite';
Database::$dbName = 'grades'; // Becomes 'grades.db'
Database::$dbPath = './my_data/'; // Directory for the DB file

$pdo = Database::connect();
if ($pdo instanceof PDO) {
    echo "Connection to SQLite successful!";
    // Perform database operations...
    Database::closeConnection();
} else {
    echo "Connection failed: " . $pdo; // $pdo contains error message
}
                        

Recommendations for connection.php:

  • Ensure appropriate PHP database drivers (PDO_SQLITE, PDO_MYSQL) are enabled.
  • Handle connection errors gracefully (e.g., log errors, display user-friendly messages).
  • For production, consider environment variables for credentials instead of hardcoding in global.php.

3.6 navgation.php (Primary Routing Logic)

The navgation.php file (or similar routing script) handles routing based on $_REQUEST parameters like submit, page, and main. It determines which file or content to load.

The logic often looks like this, typically executed after core files are loaded:

// Assuming $_MAIN_PAGE_PATH is defined, e.g., in global.php or earlier
// $_MAIN_PAGE_PATH could be 'templates/login.php' or 'templates/dashboard.php'

if (!isset($_REQUEST['submit'])) {
    if (!isset($_REQUEST['page'])) {
        if (!isset($_REQUEST['main'])) {
            // No 'submit', 'page', or 'main' - load default/main page
            if (file_exists($_MAIN_PAGE_PATH)) {
                require($_MAIN_PAGE_PATH);
            } else {
                die("Error: Main page template not found at '{$_MAIN_PAGE_PATH}'");
            }
            die(0); // Terminate after loading the main page
        } else {
            // 'main' is set (e.g., ?main=reports)
            // Route to a general section/module
            $main_route_file = "./control/route/main.php"; // Or specific logic
            if (file_exists($main_route_file)) {
                require($main_route_file);
            } else {
                die("Error: Main route handler not found.");
            }
        }
    } else {
        // 'page' is set (e.g., ?page=user_profile)
        // Route to a specific page
        $page_route_file = "./control/route/page.php"; // Or specific logic
        if (file_exists($page_route_file)) {
            require($page_route_file);
        } else {
            die("Error: Page route handler not found.");
        }
    }
} else {
    // 'submit' is set (e.g., form submission with name="submit" value="login_action")
    // Route to an action handler
    // This could be the root action.php or a specific one like ./control/route/action.php
    $action_file = "./action.php"; // More common
    // $action_file = "./control/route/action.php"; // As per path.md for specific routing
    if (file_exists($action_file)) {
        require($action_file);
    } else {
        die("Error: Action handler not found.");
    }
}
                        

Workflow Explanation:

ConditionAction Taken
No submit, page, or mainLoad $_MAIN_PAGE_PATH (e.g., login or dashboard) and terminate.
main is setLoad ./control/route/main.php (handles main sections).
page is set (but not submit)Load ./control/route/page.php (handles specific pages).
submit is setLoad ./action.php (or ./control/route/action.php) to process form submissions.

Recommendations for navgation.php:

  • File Existence: Always check if files exist before requiring them.
  • Security: Sanitize $_REQUEST values if they are used to construct file paths or in database queries directly (though typically they select pre-defined routes).
  • Clarity: For complex applications, consider a more structured routing approach or a dedicated routing library.
  • The $_MAIN_PAGE_PATH variable should be reliably defined, often pointing to a default landing page like templates/login.php or templates/dashboard.php after login.

3.7 action.php (User Action Handler)

The action.php file handles actions triggered by user input, typically form submissions via the submit parameter in $_REQUEST. It uses a switch statement to route to the appropriate logic.

Core Logic:

// Sanitize the input for security
$submit_action = htmlspecialchars($_REQUEST['submit'] ?? '');

switch ($submit_action) {
    case 'save':
        // Code to save data
        // Example: saveData();
        echo "Save action triggered.";
        break;

    case 'delete':
        // Code to delete data
        // Example: deleteData();
        echo "Delete action triggered.";
        break;

    case 'update':
        // Code to update data
        // Example: updateData();
        echo "Update action triggered.";
        break;
    
    case 'login':
        // Code to handle login
        // Example: handleLogin();
        echo "Login action triggered.";
        break;

    default:
        // Code for unrecognized or invalid actions
        echo "Error: Invalid action '{$submit_action}'.";
        break;
}

// --- Example helper functions (could be in this file or included) ---
/*
function saveData() {
    // Actual save logic
    if (isset($_POST['username'], $_POST['email'])) {
        // process and save
        echo "Data for user: " . htmlspecialchars($_POST['username']) . " saved.";
    } else {
        echo "Error: Missing data for save action.";
    }
}

function deleteData() {
    // Actual delete logic
    if (isset($_POST['item_id'])) {
        // process and delete
        echo "Item ID: " . htmlspecialchars($_POST['item_id']) . " marked for deletion.";
    } else {
        echo "Error: Missing item_id for delete action.";
    }
}
*/
                        

How It Works:

  1. Input Parameter: The submit parameter is obtained from $_REQUEST (e.g., from a form button).
    <form method="POST" action="action.php">
        <button type="submit" name="submit" value="save">Save</button>
        <button type="submit" name="submit" value="delete">Delete</button>
    </form>
  2. Switch Statement: Executes code based on the submit value.
  3. Default Case: Handles unexpected submit values.

Recommendations for action.php:

  • Validation & Sanitization: ALWAYS validate and sanitize ALL user inputs (not just $_REQUEST['submit'], but all $_POST or $_GET data used by the actions).
  • Error Handling: Provide clear error messages or redirect to error pages.
  • Modular Code: Extract action-specific logic into dedicated functions or class methods for maintainability.
  • CSRF Protection: Implement CSRF tokens for all state-changing actions.
  • Post-Action Redirect: After processing an action (especially POST requests), redirect the user to another page (Post/Redirect/Get pattern) to prevent issues with browser refresh/back button.

3.8 control/route.php (Fallback/Documentation Routing)

The control/route.php file, as described in path.md, primarily serves as a routing mechanism when the _doc (documentation) folder is not present or is empty. It's included by functions.php under these conditions.

Its role might be to set up a very basic routing for the application if the more sophisticated navgation.php isn't used or if it's an initial, simpler routing step.

Conceptual Logic:

// In control/functions.php (simplified)
function determineInitialRoute() {
    $docPath = '_doc'; // Path to documentation
    $docIndex = $docPath . '/index.php';

    if (is_dir($docPath) && file_exists($docIndex) && count(glob($docPath . '/*.md')) > 0) {
        // If _doc directory and index.php exist and there are .md files, load documentation
        require_once($docIndex);
    } else {
        // Otherwise, load the fallback/application route handler
        require_once('control/route.php');
    }
}

determineInitialRoute();

// --- Content of control/route.php (example) ---
// This file might handle basic page loading if no other router is active yet,
// or if it's a very simple application.
/*
echo "<h1>Application Mode</h1>";
echo "<p>Documentation not found or empty. Loading main application.</p>";

// It could define a default page to include if $_MAIN_PAGE_PATH is not yet set
if (!isset($_MAIN_PAGE_PATH) || !file_exists($_MAIN_PAGE_PATH)) {
    $_MAIN_PAGE_PATH = 'templates/default_app_page.php'; // A generic landing page
}

// If navgation.php is meant to be the primary router,
// control/route.php might simply ensure navgation.php is loaded,
// or set up minimal context for it.
if (file_exists('control/navgation.php')) {
    // require_once('control/navgation.php'); // This might cause double inclusion if already in index.php
} else {
    // Or, if navgation.php is not present, this route.php might contain
    // a simplified version of the routing logic itself.
    // For example, loading a default template:
    // if (file_exists('templates/home.php')) {
    //    require 'templates/home.php';
    // } else {
    //    echo "Welcome to the application!";
    // }
}
*/
                        

The exact behavior of control/route.php depends on the overall application flow. If navgation.php is the main router (included via index.php or global.php), then control/route.php's role is more of an initial condition handler or a very minimal fallback. If navgation.php is *only* included via control/route.php, then control/route.php acts as a gateway to the main routing logic.

Key Considerations:

  • This file ensures the application has some routing logic even if the documentation system isn't active.
  • It can act as a bridge to the more complex navgation.php or provide very basic routing itself.
  • Its interaction with $_MAIN_PAGE_PATH and other global routing variables is important.

4. Deployment Guide

Step 1: Set Up the Project Directory

  1. Create a root directory for your project (e.g., myRabbitApp).
  2. Organize framework files into subfolders:
    • control/: For control.php, functions.php, global.php, connection.php, navgation.php, route.php.
    • templates/: For HTML/PHP view templates (e.g., login.php, dashboard.php).
    • models/: For data models or business logic classes.
    • _doc/: (Optional) For Markdown documentation files and _doc/index.php.
    • assets/: For CSS, JS, images, fonts.
    • data/: (Or as configured) For SQLite database files or JSON data files. Ensure this directory is writable by the web server if creating/updating files.
    • Root: index.php, action.php.
    • modal/composer/: (If using Composer) For autoload.php and vendor libraries.

Step 2: Configure PHP Environment

  1. Install PHP (version 8.0 or higher recommended).
  2. Enable required PHP extensions:
    • pdo_sqlite (for SQLite).
    • pdo_mysql (if using MySQL).
    • Appropriate ODBC drivers (if using MS Access).
    • mbstring (often used by libraries like Parsedown).

Step 3: Initialize the Framework (Configuration)

  1. Configure control/global.php:
    • Set Database::$dbType, Database::$dbName, Database::$dbPath, etc.
      // Example for SQLite in global.php
      Database::$dbType = 'sqlite';
      Database::$dbName = 'app_database'; // Will create app_database.db
      Database::$dbPath = './data/';     // Ensure this path is relative to index.php and writable
                                      
    • Ensure paths for loading models, templates ($controller->requireAllPhpFiles('./models'), etc.) are correct relative to index.php.
    • Define $lable array with application metadata.
  2. Configure Routing (control/navgation.php and potentially control/route.php):
    • Define $_MAIN_PAGE_PATH, typically pointing to a default template like templates/login.php or templates/dashboard.php. This might be set conditionally (e.g., based on session).
    • Ensure the routing logic correctly includes page/action handlers from paths like ./control/route/main.php, ./control/route/page.php, and ./action.php.

Step 4: Create Sample Templates and Actions

  1. Create HTML/PHP templates in templates/ (e.g., login.php).
    <!-- templates/login.php -->
    <form method="POST" action="action.php">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <button type="submit" name="submit" value="login">Login</button>
    </form>
  2. Implement corresponding logic in action.php for form submissions.

Step 5: Test File Inclusion and Permissions

  1. Use methods from control.php to verify file loading.
    // In a test script or temporarily in index.php
    $controller = new control();
    $templates = $controller->getAllPhpFilesTemplate('./templates');
    print_r($templates); // Check if template paths are correctly found
                                    
  2. Ensure directories that need to be written to (e.g., data/ for SQLite, session save path if custom) have correct write permissions for the web server user (e.g., www-data, apache).

Step 6: Deploy Locally

  1. Navigate to your project's root directory in the terminal.
  2. Start a local PHP development server: php -S localhost:8000.
  3. Access your application at http://localhost:8000 in a browser.

Step 7: Deploy to a Web Server (e.g., Apache, Nginx)

  1. Upload all project files to your web server's document root (e.g., /var/www/html/myRabbitApp or public_html/myRabbitApp).
  2. Configure the web server:
    • Ensure PHP is correctly configured to process .php files.
    • Set up URL rewriting (e.g., .htaccess for Apache) if you want cleaner URLs (e.g., hide index.php). A basic .htaccess for routing all requests through index.php (if not already handled by file structure):
      RewriteEngine On
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule ^(.*)$ index.php [L,QSA]
      (Note: RabbitLite's current structure seems to rely on direct file access or query parameters, so complex rewriting might not be immediately necessary unless you evolve the routing.)
    • Verify file permissions again on the server.
  3. Access your application via its public URL.

5. Sample Application Setup (Login System Example)

This example demonstrates a basic login system.

1. Configuration (control/global.php)

Database::$dbType = 'sqlite';
Database::$dbName = 'users'; // Will be users.db
Database::$dbPath = './data/'; // Ensure './data/' exists and is writable
// ... other global settings ...

// Initialize $controller
// $controller = new control(); // Assuming control.php is already included

// Get template paths
// $temp = $controller->getAllPhpFilesTemplate('./templates');

// Initial main page (before login)
// $_MAIN_PAGE_PATH = $temp['login'] ?? 'templates/login.php'; // Set default if not found
                    

2. Login Template (templates/login.php)

<h3>Login</h3>
<?php if (isset($_SESSION['error_message'])): ?>
    <p style="color:red;"><?= htmlspecialchars($_SESSION['error_message']); ?></p>
    <?php unset($_SESSION['error_message']); ?>
<?php endif; ?>

<form method="POST" action="action.php">
    Username: <input type="text" name="username" required><br>
    Password: <input type="password" name="password" required><br>
    <button type="submit" name="submit" value="login">Login</button>
</form>

3. Dashboard Template (templates/dashboard.php)

<h3>Dashboard</h3>
<p>Welcome, <?= htmlspecialchars($_SESSION['username'] ?? 'Guest'); ?>!</p>
<form method="POST" action="action.php">
    <button type="submit" name="submit" value="logout">Logout</button>
</form>

4. Action Logic (action.php)

<?php
// Ensure session is started (usually in index.php)
// session_start(); 

// Ensure Database class is available (usually via global.php)
// require_once './control/connection.php'; // If not already loaded

$submit_action = htmlspecialchars($_REQUEST['submit'] ?? '');

switch ($submit_action) {
    case 'login':
        // Basic login logic (replace with proper user authentication)
        $username = $_POST['username'] ?? '';
        $password = $_POST['password'] ?? '';

        // Example: connect to DB and check credentials
        // Database::$dbType = 'sqlite'; // Assuming already set in global.php
        // Database::$dbName = 'users';
        // Database::$dbPath = './data/';
        // $pdo = Database::connect();

        // This is a placeholder for actual user validation
        if ($username === 'admin' && $password === 'password') { // NEVER do this in production
            $_SESSION['user_id'] = 1; // Example user ID
            $_SESSION['username'] = $username;
            header('Location: index.php?main=dashboard'); // Redirect to dashboard
            exit;
        } else {
            $_SESSION['error_message'] = 'Invalid username or password.';
            header('Location: index.php'); // Redirect back to login page
            exit;
        }
        break;

    case 'logout':
        session_unset();
        session_destroy();
        header('Location: index.php'); // Redirect to login page
        exit;
        break;
        
    // ... other cases ...
    default:
        echo "Invalid action: " . htmlspecialchars($submit_action);
        // Optionally redirect to an error page or home page
        // header('Location: index.php?error=invalid_action');
        // exit;
        break;
}
?>

5. Routing Logic (control/navgation.php)

<?php
// Ensure session is started (usually in index.php)
// session_start();

// $_MAIN_PAGE_PATH should be defined, e.g., in global.php or here
// Get template paths if not already available
// $controller = new control(); // Assuming control.php included
// $temp = $controller->getAllPhpFilesTemplate('./templates');

// Determine default page based on login status
if (isset($_SESSION['user_id'])) {
    $_MAIN_PAGE_PATH = 'templates/dashboard.php'; // User is logged in
} else {
    $_MAIN_PAGE_PATH = 'templates/login.php';     // User is not logged in
}


if (!isset($_REQUEST['submit'])) { // Actions are handled by action.php
    if (!isset($_REQUEST['page'])) {
        if (!isset($_REQUEST['main'])) {
            // Default: No specific 'page' or 'main' parameter
            if (file_exists($_MAIN_PAGE_PATH)) {
                require($_MAIN_PAGE_PATH);
            } else {
                die("Error: Main page template '{$_MAIN_PAGE_PATH}' not found.");
            }
            die(0); 
        } else {
            // Handle 'main' parameter (e.g., ?main=dashboard)
            $main_target = htmlspecialchars($_REQUEST['main']);
            if ($main_target === 'dashboard' && isset($_SESSION['user_id'])) {
                if (file_exists('templates/dashboard.php')) {
                    require('templates/dashboard.php');
                } else {
                    die("Dashboard template not found.");
                }
            } else if ($main_target === 'dashboard' && !isset($_SESSION['user_id'])) {
                // Trying to access dashboard without login, redirect to login
                header('Location: index.php');
                exit;
            }
            // Add more 'main' routes here
            // else { require("./control/route/main.php"); // Generic handler }
        }
    } else {
        // Handle 'page' parameter (e.g., ?page=settings)
        // require("./control/route/page.php"); // Generic page handler
        // Or specific page logic
        $page_target = htmlspecialchars($_REQUEST['page']);
        // if ($page_target === 'settings' && file_exists('templates/settings.php')) {
        //    require 'templates/settings.php';
        // }
    }
} 
// 'submit' actions are handled by action.php, which should be included/required by index.php 
// or routed to by navgation.php if 'submit' is present
// The example navgation.php provided in its markdown suggests action.php is included if 'submit' is set.
// So, if this navgation.php itself is included when submit is NOT set, then another routing mechanism
// (perhaps in index.php or a top-level router) would direct to action.php when 'submit' IS set.

// An alternative structure for navgation.php if it's the *sole* router:
/*
if (isset($_REQUEST['submit'])) {
    require 'action.php'; // Process actions first
    // action.php should handle redirects or die, otherwise navgation continues
} elseif (isset($_REQUEST['main'])) {
    // ... main logic ...
    $main_target = htmlspecialchars($_REQUEST['main']);
    if ($main_target === 'dashboard' && isset($_SESSION['user_id'])) {
        require 'templates/dashboard.php';
    } // etc.
} elseif (isset($_REQUEST['page'])) {
    // ... page logic ...
} else {
    // Default page
    if (isset($_SESSION['user_id'])) {
        require 'templates/dashboard.php'; 
    } else {
        require 'templates/login.php';
    }
}
*/
?>

Note: The action.php should always perform a redirect (header('Location: ...'); exit;) after a POST request to prevent form resubmission issues (PRG pattern). The routing in navgation.php or index.php will then display the new page.

6. General Recommendations

Security

  1. Input Sanitization & Validation:
    • Sanitize ALL user inputs ($_GET, $_POST, $_REQUEST, $_COOKIE) to prevent XSS, SQL Injection, etc. Use functions like htmlspecialchars() for outputting data, and prepared statements (PDO) for database queries.
    • Validate data types, formats, lengths, and ranges.
  2. CSRF Protection: Implement Cross-Site Request Forgery tokens for all forms that perform state-changing actions.
  3. Session Security:
    • Regenerate session ID after login (session_regenerate_id(true);).
    • Use appropriate session cookie settings (HttpOnly, Secure, SameSite).
  4. File Permissions: Set the strictest possible file and directory permissions. Only allow write access where absolutely necessary (e.g., data directories, cache).
  5. Error Reporting: Disable display of detailed errors in production (display_errors = Off in php.ini). Log errors to a file instead.
  6. HTTPS: Always use HTTPS for secure data transmission.
  7. Dependencies: Keep third-party libraries (like Parsedown, or any Composer packages) up to date.

Error Handling

  1. Provide clear, user-friendly error messages. Avoid exposing sensitive system information.
  2. Implement robust logging for errors and important events for debugging and auditing.
  3. Check return values of file operations, database calls, etc., and handle failures gracefully.

Code Quality & Maintainability

  1. Modularity: Break down logic into smaller, reusable functions or class methods (as suggested for action.php and control.php).
  2. Consistency: Maintain a consistent coding style and naming conventions.
  3. Comments: Write clear and concise comments to explain complex logic or non-obvious code.
  4. DRY Principle: Don't Repeat Yourself. Abstract common functionality.
  5. Configuration Management: Separate configuration from code (e.g., use global.php effectively, consider environment variables for production).

Scalability & Performance

  1. Database Optimization: Use efficient database queries, appropriate indexing, and connection pooling if applicable.
  2. Caching: Implement caching for frequently accessed data or computationally expensive operations (e.g., results from control.php file scans if directories don't change often, parsed Markdown).
  3. Composer: Use Composer for managing third-party dependencies, which helps with updates and autoloading.
  4. Routing: For larger applications, consider a more advanced routing component or library for better organization and features.

7. Contact & Support (iQuipe Digital)

iQuipe digital is a company specializing in cloud solutions and software development. We help businesses leverage the power of the cloud and build custom software to meet their unique needs.

Get in Touch:

Connect With Us:

For inquiries about cloud services, software development expertise, or to discuss project requirements, please feel free to reach out via email or through the website contact form.