MCCodes - Chapter 2: Global Setup & Session Management

MCCodes Walkthrough Tutorial

Welcome back! In Chapter 1: Page Rendering & Structure, we learned how MCCodes uses a blueprint (header.php and $h) and a style guide (css/game.css) to make every page look consistent. But before the game can even start drawing the page layout, it needs to figure out some crucial things: Are you logged in to the game? Who are you? Are you allowed to be on this page?

This chapter explains the foundational system that handles these essential startup tasks: Global Setup & Session Management.

The Problem: Setting the Stage Before the Play

Imagine walking into a game world. Before you can explore or do anything, the game needs to:

  1. Recognize You: Check if you've logged in and remember who you are.
  2. Connect to the World's Rules: Load the basic settings and rules of the game world.
  3. Fetch Your Character Sheet: Get your specific player details (stats, money, events, etc.).
  4. Check Security: Make sure you're not banned or supposed to be somewhere else (like jail).
  5. Prepare the View: Get the page builder ($h from Chapter 1) ready.

Without this setup, the game wouldn't know who you are, how much health you have, or any of your other basic stats like will or energy! Every single page for a logged-in user needs this same initial setup.

The Solution: globals.php - The Master Switch

MCCodes solves this by having a central setup file: globals.php. Think of it like the main power switch and control panel for a building. Before anyone can use any room (any game page), this panel needs to be activated to turn on the lights (database connection), check security badges (sessions), and provide basic information (settings and user data).

Almost every game file that requires you to be logged in starts by including globals.php. This one line triggers a whole sequence of essential setup steps.

<?php
// Example start of a game file like inventory.php
require 'globals.php'; // <-- This does all the magic setup!

// ... rest of the page code starts here ...
?>

Let's break down what globals.php does when it runs.

1. Remembering Who You Are (Session Management)

When you log in, the game needs a way to remember you as you click from page to page. It does this using sessions.

globals.php starts by managing this session:

// Inside globals.php (Simplified Concept)

session_name('MCCSID'); // Give the session cookie a specific name
session_start();      // Start or resume the session (read the badge)

// Check if the user is actually marked as logged in
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] == 0)
{
    // If not logged in, send them back to the login page
    header("Location: login.php");
    exit; // Stop loading this page
}

// Get the User ID from the session
$userid = (int) ($_SESSION['userid'] ?? 0);

(Note: Session management is a core PHP feature. globals.php just uses it to store and check login status and user ID.)

2. Connecting to the Game's Brain (Database Connection)

All the game data -- player stats, items, settings, etc. -- is stored in a database. globals.php is responsible for establishing the connection to this database.

// Inside globals.php (Simplified Concept)

// Include database configuration (hostname, username, password, db name)
include 'config.php';
// Include the database class file (instructions on how to talk to the DB)
require "class/class_db_{$_CONFIG['driver']}.php";

// Create a database connection object
$db = new database();
$db->configure(/* ... credentials from config.php ... */);
$db->connect();

This code:

(Note: Using global $db; in functions later is common in MCCodes to access this connection, which isn't always considered the best modern practice, but it's how this system works.)

3. Loading the Game Rules (Site Settings)

Every game needs configurable settings -- the game's name, specific rules, feature toggles, etc. globals.php loads these from the database into an array called $set.

// Inside globals.php (Simplified Concept)

// Function to load settings (defined elsewhere, e.g., in global_func.php)
$set = get_site_settings();

The get_site_settings() function (defined in global_func.php) queries the settings table in the database and loads all the key-value pairs into the $set array. Now, any page can check a setting like $set['game_name'] to display the game's title.

4. Fetching Your Character Sheet ($ir variable)

Now that the game knows your $userid (from the session) and is connected to the database, it fetches your specific player data. This is stored in a crucial array variable named $ir (often stands for "Information Row" or "User Row").

// Inside globals.php (Simplified Concept)

// Query the database for the user's data based on $userid
$is = $db->query("SELECT u.*, us.*
                  FROM users u
                  INNER JOIN userstats us ON u.userid = us.userid
                  WHERE u.userid = {$userid}");

// Fetch the data into the $ir array
$ir = $db->fetch_row($is);
// (Also includes code to make sure data types are correct)

This code performs a database query to select all columns (*) from the users table and the userstats table for the row matching the logged-in $userid. The result is stored in the $ir array. Now, any page can access your data like $ir['username'], $ir['level'], $ir['money'], $ir['hp'], etc.

5. Performing Security Checks

Before letting you proceed, globals.php runs some vital security and status checks.

// Inside globals.php (Simplified Concept)

// Check if an admin forced this user to log out
if ($ir['force_logout'] > 0) {
    // Clear the session and redirect to login
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit;
}

// Check if the user is in Federal Jail (using data in $ir)
if ($ir['fedjail'] > 0) {
     // Display jail message and stop loading page
     die("You are in Federal Jail...");
}

// Check for IP Bans (code checks if current IP is banned)
if (file_exists('ipbans/' . $_SERVER['REMOTE_ADDR'])) {
     // Display banned message and stop loading page
     die("Your IP has been banned...");
}

// Check if the user needs to complete validation (macro check)
// ... (code for macro check redirects if needed) ...

// Update user's level if they have enough experience
check_level();

These checks ensure that players who should be logged out are logged out, banned players or IPs are stopped, and jailed players see the correct message instead of the game page. It also handles things like level-ups via the check_level() function. We'll touch more on security aspects in Chapter 9: Security Functions (CSRF/Password/Validation).

6. Initializing the Page Builder ($h)

Finally, after all the checks and data loading are done, globals.php gets the page structure ready, just like we learned in Chapter 1.

// Inside globals.php (Simplified Concept)

// Include the header class file
require 'header.php';

// Create the header object
$h = new headers();

// Start building the page (unless told not to by $nohdr)
if (!isset($nohdr) || !$nohdr) {
    $h->startheaders(); // Output HTML head, CSS link, start layout
    $h->userdata($ir /* ... other args ... */); // Display user sidebar
    $h->menuarea();     // Display main navigation menu
}

This creates the $h object and calls its initial methods to output the top part of the HTML, the user information sidebar (using the $ir data it just loaded), and the main navigation menu. The page is now ready for the specific game file (like inventory.php) to add its unique content.

How It All Flows Together

Let's visualize the sequence when you request a page like inventory.php:

sequenceDiagram
    participant B as Browser
    participant S as Server (inventory.php)
    participant G as globals.php
    participant DB as Database
    participant H as header.php ($h object)

    B->>S: Request inventory.php
    S->>G: require 'globals.php'
    G->>G: Start Session (session_start)
    G->>G: Check if logged in (using $_SESSION)
    Note over G: If not logged in, redirect to login.php & exit.
    G->>DB: Connect to Database ($db)
    G->>DB: Load Site Settings ($set)
    G->>DB: Load User Data for $userid ($ir)
    G->>G: Perform Security Checks (bans, jail, etc.)
    G->>H: Create $h object (new headers())
    G->>H: $h->startheaders()
    H-->>B: Send HTML head, CSS link...
    G->>H: $h->userdata($ir, ...)
    H->>DB: Update user's last active time
    H-->>B: Send User Stats Sidebar HTML
    G->>H: $h->menuarea()
    H-->>B: Send Menu HTML & Content Area Start
    G-->>S: globals.php finishes
    S->>S: Generate unique inventory content (HTML)
    S-->>B: Send Inventory List HTML
    S->>H: $h->endpage()
    H-->>B: Send closing HTML tags

As you can see, globals.php acts as the critical first step, orchestrating sessions, database connections, data loading, security, and the initial page structure setup before the actual page file (inventory.php in this example) even begins its specific task.

Special Cases: globals_nonauth.php and sglobals.php

Key Files Summary

Conclusion

You've now learned about the critical globals.php file and its role in setting the stage for almost every logged-in page view in MCCodes. It's the invisible foundation that:

Without globals.php, none of the dynamic, player-specific content could be displayed, and the game wouldn't function. It truly is the main power switch and control panel for the game world.

Now that we understand how the game recognizes you and prepares the basic environment, let's look at one of the core gameplay loops you might encounter: committing crimes.


Next Up: Chapter 3: Crime System

Previously: Chapter 1: Page Rendering & Structure


First published April 21, 2025

Tags: MCCodes Walkthrough Tutorial