PHP, HTML & Web Development

The examples on this page demonstrate my experience building database-driven and interactive web applications using PHP, MySQL, HTML5, CSS, and related web technologies. Rather than focusing on isolated code snippets, these examples illustrate how I combine server-side programming, database connectivity, user interaction, and modern web-page structure to create functional applications. Together, they provide a practical look at my ability to take a web-development requirement from concept through implementation. These examples are presented as demonstrations of coding techniques and application structure. They are not intended to represent complete, production-ready applications.

PHP/MySQL/HTML Member Authentication & 2FA System

This example demonstrates a complete database-driven member authentication application built with PHP, MySQL, and HTML. The application uses a structured controller-and-view approach to manage configuration, secure sessions, database connectivity, reusable helper functions, user login, two-factor authentication (2FA), and conditional rendering of the appropriate user interface. By bringing these components together in a single application, this example demonstrates my ability to develop secure, interactive web applications that combine server-side programming, database operations, authentication, and front-end presentation into a cohesive solution.

<?php
/**
 * SECURE USER AUTHENTICATION EXAMPLE
 * Features: Registration, Login, Logout, 2FA (TOTP), Session Security, CSRF Protection
 */

// --- 1. CONFIGURATION ---
$db_config = [
    'host' => 'localhost',
    'name' => 'my_secure_app',
    'user' => 'root', // Replace with your DB user
    'pass' => ''      // Replace with your DB password
];

// --- 2. SESSION SECURITY ---
// Set session cookie parameters before starting the session
session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => '', 
    'secure' => isset($_SERVER['HTTPS']), // Only send over HTTPS if available
    'httponly' => true,                   // Prevent JavaScript access to session cookie
    'samesite' => 'Strict'                // Mitigate CSRF attacks
]);

session_start();

// --- 3. DATABASE CONNECTION (PDO) ---
try {
    $pdo = new PDO(
        "mysql:host={$db_config['host']};dbname={$db_config['name']};charset=utf8mb4",
        $db_config['user'],
        $db_config['pass'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
    );
} catch (PDOException $e) {
    die("Connection failed: " . htmlspecialchars($e->getMessage()));
}

// --- 4. HELPER FUNCTIONS ---
function generate_csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function verify_csrf_token($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Simple mock for 2FA validation (In production, use a library like 'robthree/twofactorauth')
function verify_2fa_code($secret, $code) {
    // This is a placeholder. A real TOTP implementation would check the 
    // 6-digit code against the secret and current time.
    return ($code === "123456"); // For demo purposes, '123456' is always valid
}

// --- 5. CONTROLLER LOGIC (Action Routing) ---
$error = '';
$message = '';
$action = $_GET['action'] ?? 'home';

// Handle Logout
if ($action === 'logout') {
    $_SESSION = [];
    session_destroy();
    header("Location: index.php");
    exit;
}

// Handle POST Requests (Login / Register / 2FA)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        die("CSRF token validation failed.");
    }

    $form_type = $_POST['form_type'];

    // REGISTRATION
    if ($form_type === 'register') {
        $user = trim($_POST['username']);
        $email = trim($_POST['email']);
        $pass = $_POST['password'];

        if (empty($user) || !filter_var($email, FILTER_VALIDATE_EMAIL) || strlen($pass) < 8) {
            $error = "Invalid input. Password must be at least 8 characters.";
        } else {
            $hashed_pass = password_hash($pass, PASSWORD_DEFAULT);
            $stmt = $pdo->prepare("INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)");
            try {
                $stmt->execute([$user, $email, $hashed_pass]);
                $message = "Registration successful! You can now log in.";
                $action = 'login';
            } catch (PDOException $e) {
                $error = "Username or Email already exists.";
            }
        }
    }

    // LOGIN (Step 1: Password)
    elseif ($form_type === 'login') {
        $user = trim($_POST['username']);
        $pass = $_POST['password'];

        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$user]);
        $db_user = $stmt->fetch();

        if ($db_user && password_verify($pass, $db_user['password_hash'])) {
            // Check if 2FA is required
            if ($db_user['is_2fa_enabled']) {
                $_SESSION['temp_user_id'] = $db_user['id'];
                $action = 'verify_2fa';
            } else {
                // No 2FA, complete login
                session_regenerate_id(true);
                $_SESSION['user_id'] = $db_user['id'];
                $_SESSION['username'] = $db_user['username'];
                header("Location: index.php?action=dashboard");
                exit;
            }
        } else {
            $error = "Invalid username or password.";
        }
    }

    // 2FA VERIFICATION (Step 2)
    elseif ($form_type === 'verify_2fa') {
        $code = $_POST['otp_code'];
        $user_id = $_SESSION['temp_user_id'] ?? null;

        if ($user_id) {
            $stmt = $pdo->prepare("SELECT username, two_factor_secret FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $db_user = $stmt->fetch();

            if (verify_2fa_code($db_user['two_factor_secret'], $code)) {
                session_regenerate_id(true);
                $_SESSION['user_id'] = $user_id;
                $_SESSION['username'] = $db_user['username'];
                unset($_SESSION['temp_user_id']);
                header("Location: index.php?action=dashboard");
                exit;
            } else {
                $error = "Invalid 2FA code.";
                $action = 'verify_2fa';
            }
        }
    }
}

// --- 6. VIEW LOGIC (HTML) ---
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Secure App Example</title>
    <style>
        body { font-family: sans-serif; background: #f4f4f9; padding: 50px; }
        .container { max-width: 400px; background: white; padding: 20px; margin: auto; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .error { color: red; } .message { color: green; }
        input { width: 100%; padding: 10px; margin: 10px 0; box-sizing: border-box; }
        button { width: 100%; padding: 10px; background: #007bff; color: white; border: none; cursor: pointer; }
    </style>
</head>
<body>
<div class="container">
    <?php if ($error): ?><p class="error"><?= htmlspecialchars($error) ?></p><?php endif; ?>
    <?php if ($message): ?><p class="message"><?= htmlspecialchars($message) ?></p><?php endif; ?>

    <?php if (isset($_SESSION['user_id'])): ?>
        <!-- LOGGED IN VIEW -->
        <h2>Welcome, <?= htmlspecialchars($_SESSION['username']) ?>!</h2>
        <p>This is your secure dashboard.</p>
        <p><a href="?action=logout">Logout</a></p>

    <?php elseif ($action === 'verify_2fa'): ?>
        <!-- 2FA VERIFICATION VIEW -->
        <h2>2-Factor Authentication</h2>
        <p>Enter the 6-digit code from your app. (Try 123456 for this demo)</p>
        <form method="POST">
            <input type="hidden" name="form_type" value="verify_2fa">
            <input type="hidden" name="csrf_token" value="<?= generate_csrf_token() ?>">
            <input type="text" name="otp_code" placeholder="000000" required autofocus>
            <button type="submit">Verify Code</button>
        </form>

    <?php elseif ($action === 'register'): ?>
        <!-- REGISTRATION VIEW -->
        <h2>Create Account</h2>
        <form method="POST">
            <input type="hidden" name="form_type" value="register">
            <input type="hidden" name="csrf_token" value="<?= generate_csrf_token() ?>">
            <input type="text" name="username" placeholder="Username" required>
            <input type="email" name="email" placeholder="Email" required>
            <input type="password" name="password" placeholder="Password (min 8 chars)" required>
            <button type="submit">Sign Up</button>
        </form>
        <p>Already have an account? <a href="?action=login">Login here</a></p>

    <?php else: ?>
        <!-- LOGIN VIEW (Default) -->
        <h2>Login</h2>
        <form method="POST">
            <input type="hidden" name="form_type" value="login">
            <input type="hidden" name="csrf_token" value="<?= generate_csrf_token() ?>">
            <input type="text" name="username" placeholder="Username" required>
            <input type="password" name="password" placeholder="Password" required>
            <button type="submit">Login</button>
        </form>
        <p>No account? <a href="?action=register">Register here</a></p>
    <?php endif; ?>
</div>
</body>
</html>

Device-Specific Report Delivery

These examples demonstrate two approaches I have used to deliver reporting interfaces tailored to the user’s device. The first uses PHP for server-side device detection, allowing the application to determine the appropriate reporting interface before the page is delivered. The second uses JavaScript for client-side detection, allowing the browser to determine the appropriate experience after the page has loaded. Presenting both approaches illustrates my understanding of the distinction between server-side and client-side processing and the practical considerations involved in designing reporting applications for different devices.

PHP Server-Side Detection

<?php
// Function to detect if the user is on a mobile device
function isMobile() {
    return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}

// Logic to determine which file to load
if (isMobile()) {
    $reportPage = 'reports_mobile.php';
    $deviceType = "Mobile";
} else {
    $reportPage = 'reports_pc.php';
    $deviceType = "Desktop/PC";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Executive Reporting Dashboard</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; background-color: #f5f7fa; }
        .header { background: #333; color: gold; padding: 20px; text-align: center; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .container { padding: 20px; max-width: 1200px; margin: auto; }
        .status-bar { background: #eef1f4; padding: 10px; font-size: 0.8em; text-align: right; border-bottom: 1px solid #ddd; }
    </style>
</head>
<body>

    <div class="status-bar">
        System detected: <strong><?php echo $deviceType; ?></strong>
    </div>

    <div class="header">
        <h1>Global Operations Report</h1>
    </div>

    <div class="container">
        <!-- 
           This PHP include pulls in the specific report file 
           based on the device detection logic above. 
        -->
        <?php include($reportPage); ?>
    </div>

</body>
</html>

JavaScript Client-Side Detection

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Redirecting to Report...</title>
    
    <script>
        (function() {
            // Check for mobile devices using userAgent and screen width
            const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) 
                             || (window.innerWidth <= 768);

            if (isMobile) {
                // Redirect to the mobile PHP page
                window.location.href = "reports_mobile.php";
            } else {
                // Redirect to the desktop PHP page
                window.location.href = "reports_pc.php";
            }
        })();
    </script>
    
    <style>
        body { display: flex; justify-content: center; align-items: center; height: 100vh; font-family: sans-serif; }
        .loader { text-align: center; }
    </style>
</head>
<body>
    <div class="loader">
        <h2>Loading optimized report...</h2>
        <p>Detecting device hardware for best experience.</p>
    </div>
</body>
</html>