MCCodes - Chapter 2: Global Setup & Session Management
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:
- Recognize You: Check if you've logged in and remember who you are.
- Connect to the World's Rules: Load the basic settings and rules of the game world.
- Fetch Your Character Sheet: Get your specific player details (stats, money, events, etc.).
- Check Security: Make sure you're not banned or supposed to be somewhere else (like jail).
- 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.
- Analogy: Think of logging in as getting a temporary ID badge when you enter a building. As you walk around, security guards (the server) just need to glance at your badge (the session) to know you're allowed in and who you are.
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);
-
session_name()
: Sets a unique name for the game's session cookie (like naming the type of ID badge). -
session_start()
: Tells PHP to either start a new session or resume an existing one based on the cookie sent by your browser. - Login Check: It crucially checks if the session says you are logged in (
$_SESSION['loggedin']
). If not, it immediately redirects you tologin.php
and stops loading the current page. This prevents non-logged-in users from accessing game pages. -
$userid = ...
: If you are logged in, it retrieves your unique User ID (userid
) from the session data. This ID is essential for fetching your specific player information.
(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.
- Analogy: This is like plugging the building into the main power grid and data network. Without this connection, you can't access any information.
// 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:
- Loads the database login details from
config.php
. - Uses a special
database
class (provided by MCCodes) to handle the actual connection. - Creates a
$db
object, which will be used by other parts of the game to read and write data. We'll explore this more in Chapter 10: Database Interaction.
(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
.
- Analogy: This is like fetching the building's directory and rulebook.
// 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").
- Analogy: This is like the system pulling up your personal profile or character sheet based on your ID badge.
// 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.
- Analogy: The security guard checks if your badge is still valid, if you've been flagged for removal, or if you're banned from the building.
// 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.
- Analogy: The control panel signals the construction crew (
$h
) to start building the standard room layout (header, sidebar, menu).
// 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
globals_nonauth.php
: What about pages you can see before logging in, likelogin.php
orregister.php
? They can't useglobals.php
because it forces you to be logged in! For these pages, MCCodes usesglobals_nonauth.php
. It's a much simpler version that:- Starts sessions (to handle things like login attempts).
- Connects to the database (
$db
). - Loads site settings (
$set
). - It does NOT check for login, load
$ir
, perform user security checks, or initialize$h
. The login page (authenticate.php
) uses this to connect to the DB and check credentials before then setting the$_SESSION['loggedin']
variable.
sglobals.php
: There's alsosglobals.php
. This is almost identical toglobals.php
but is used specifically for the Staff Panel pages. The main differences are:- It includes extra checks to ensure the user is actually a staff member (
is_staff()
). - It usually loads a different menu (
smenu.php
via$h->smenuarea()
) specific to staff actions. We'll cover this more in Chapter 8: Staff Panel & Permissions.
- It includes extra checks to ensure the user is actually a staff member (
Key Files Summary
-
globals.php
: The main setup file for logged-in user pages. Handles sessions, DB connection, loading$set
and$ir
, security checks, and initializing$h
. -
globals_nonauth.php
: Simplified setup for pages accessible without being logged in (e.g.,login.php
). Connects to DB, loads$set
. -
sglobals.php
: Setup file for Staff Panel pages. Similar toglobals.php
but adds staff permission checks and loads the staff menu. -
config.php
: Stores database connection details (hostname, username, password, database name). Included by the globals files. -
global_func.php
: Contains various helper functions used across the game, includingget_site_settings()
andcheck_level()
. -
class/class_db_*.php
: Contains thedatabase
class used for interacting with the database. (More in Chapter 10: Database Interaction). -
header.php
: Contains theheaders
class ($h
) used for page rendering. (Covered in Chapter 1). - Database Tables:
users
,userstats
,settings
,fedjail
, etc.
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:
- Ensures you're logged in (Session Management).
- Connects to the game's data source (Database Connection).
- Loads essential game rules (Site Settings
$set
). - Retrieves your specific player data (User Info
$ir
). - Performs crucial security checks.
- Starts the page building process (
$h
).
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