Linux cesa-www-main 6.1.0-49-cloud-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.174-1 (2026-05-26) x86_64
Apache/2.4.68 (Debian)
Server IP : 10.218.0.2 & Your IP : 216.73.216.28
Domains :
Cant Read [ /etc/named.conf ]
User : www-data
Terminal
Auto Root
Create File
Create Folder
Localroot Suggester
Backdoor Destroyer
Readme
/
var /
www /
cesa.co.za /
php /
includes /
error_handling /
Delete
Unzip
Name
Size
Permission
Date
Action
bootstrap.php
1.88
KB
-rw-r--r--
2026-06-03 05:55
error_handler.php
25.1
KB
-rw-r--r--
2026-08-24 10:24
Save
Rename
<?php /** * Comprehensive Error Handler for CESA Site * * This file provides centralized error handling for the entire CESA site, * including WordPress, native PHP, and PHPMaker applications. * * Features: * - Custom error pages for different error types * - Error logging to file and database * - Email notifications for critical errors * - Development vs production error display * - Fatal error handling */ // Prevent direct access if (!defined('CESA_ERROR_HANDLER_LOADED')) { define('CESA_ERROR_HANDLER_LOADED', true); } // Error handler configuration class CESAErrorHandler { private static $instance = null; private $logFile; private $emailNotifications = true; private $adminEmail = 'cesa-errors@igotafrica.com'; private $isDevelopment = true; private $errorCount = 0; private $maxErrors = 10; // Prevent infinite loops private $skipDatabaseLogging = false; private function __construct() { // Determine if we're in development mode $this->isDevelopment = $this->isDevelopmentEnvironment(); // Set up log file $this->logFile = $_SERVER['DOCUMENT_ROOT'] . '/logs/error.log'; // Create logs directory if it doesn't exist $logDir = dirname($this->logFile); if (!is_dir($logDir)) { mkdir($logDir, 0755, true); } // Set up error handlers $this->setupErrorHandlers(); } public static function getInstance() { if (self::$instance === null) { self::$instance = new self(); } return self::$instance; } /** * Determine if we're in a development environment */ private function isDevelopmentEnvironment() { $host = $_SERVER['HTTP_HOST'] ?? ''; $documentRoot = $_SERVER['DOCUMENT_ROOT'] ?? ''; return ( strpos($host, 'localhost') !== false || strpos($host, 'devstage') !== false || strpos($documentRoot, 'BitBucket') !== false || strpos($documentRoot, 'clients/client37') !== false ); // return true; } /** * Set up all error handlers */ private function setupErrorHandlers() { // Set error reporting level - only show fatal errors and critical errors if ($this->isDevelopment) { error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR); ini_set('display_errors', 1); } else { error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR); ini_set('display_errors', 0); } // Set custom error handler set_error_handler(array($this, 'handleError')); // Set exception handler set_exception_handler(array($this, 'handleException')); // Set shutdown function for fatal errors register_shutdown_function(array($this, 'handleFatalError')); // Set custom error handler for ADODB if it exists if (function_exists('ADODB_Error_Handler')) { // We'll override this in our handler } } /** * Handle PHP errors */ public function handleError($errno, $errstr, $errfile, $errline, $errcontext = null) { // Prevent infinite loops if ($this->errorCount++ > $this->maxErrors) { return false; } // Don't handle errors if error reporting is disabled if (error_reporting() == 0) { return false; } // Only handle critical errors that will stop the system from working if (!$this->isCriticalError($errno)) { return false; // Let PHP handle non-critical errors (warnings, notices, deprecations) } $errorType = $this->getErrorType($errno); $errorData = array( 'type' => $errorType, 'message' => $errstr, 'file' => $errfile, 'line' => $errline, 'context' => $errcontext, 'timestamp' => date('Y-m-d H:i:s'), 'url' => $_SERVER['REQUEST_URI'] ?? 'CLI', 'ip' => $_SERVER['REMOTE_ADDR'] ?? 'CLI', 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'CLI', 'trace' => $errcontext['trace'] ?? '' ); // Log the error $this->logError($errorData); // Display error page for critical errors $this->displayErrorPage($errorData); return true; // Don't execute PHP's internal error handler } /** * Handle exceptions */ public function handleException($exception) { $errorData = array( 'type' => get_class($exception), 'message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => $this->formatThrowableTrace($exception), 'timestamp' => date('Y-m-d H:i:s'), 'url' => $_SERVER['REQUEST_URI'] ?? 'CLI', 'ip' => $_SERVER['REMOTE_ADDR'] ?? 'CLI', 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'CLI' ); try { $this->logError($errorData); } catch (Throwable $e) { $errorData['trace'] .= "\n\n[error logger failed: " . $e->getMessage() . "]\n" . $e->getTraceAsString(); } $this->displayErrorPage($errorData); } /** * Handle fatal errors */ public function handleFatalError() { $error = error_get_last(); if ($error && $this->isCriticalError($error['type'])) { $errorData = array( 'type' => 'Fatal Error', 'message' => $error['message'], 'file' => $error['file'], 'line' => $error['line'], 'timestamp' => date('Y-m-d H:i:s'), 'url' => $_SERVER['REQUEST_URI'] ?? 'CLI', 'ip' => $_SERVER['REMOTE_ADDR'] ?? 'CLI', 'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'CLI', 'trace' => $this->formatFatalTrace($error) ); try { $this->logError($errorData); } catch (Throwable $e) { $errorData['trace'] .= "\n\n[error logger failed: " . $e->getMessage() . "]\n" . $e->getTraceAsString(); } $this->displayErrorPage($errorData); } } /** * Full exception chain for the error page. */ private function formatThrowableTrace($exception) { $parts = []; $current = $exception; $depth = 0; while ($current instanceof Throwable && $depth < 10) { $label = $depth === 0 ? get_class($current) : 'Caused by ' . get_class($current); $parts[] = $label . ': ' . $current->getMessage() . ' in ' . $current->getFile() . ':' . $current->getLine() . "\n" . $current->getTraceAsString(); $current = $current->getPrevious(); $depth++; } return implode("\n\n", $parts); } /** * error_get_last() has no stack; keep the PHP message (often includes a trace) * and append the shutdown backtrace. */ private function formatFatalTrace(array $error) { $parts = []; $message = (string) ($error['message'] ?? ''); if ($message !== '') { $parts[] = $message; } $shutdownTrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $lines = []; foreach ($shutdownTrace as $i => $frame) { $file = $frame['file'] ?? '[internal]'; $line = isset($frame['line']) ? ':' . $frame['line'] : ''; $fn = ($frame['class'] ?? '') . ($frame['type'] ?? '') . ($frame['function'] ?? ''); $lines[] = '#' . $i . ' ' . $file . $line . ' ' . $fn; } if ($lines) { $parts[] = "Shutdown backtrace:\n" . implode("\n", $lines); } return implode("\n\n", $parts) ?: '(no stack trace)'; } /** * Get human-readable error type */ private function getErrorType($errno) { switch ($errno) { case E_ERROR: return 'Fatal Error'; case E_WARNING: return 'Warning'; case E_PARSE: return 'Parse Error'; case E_NOTICE: return 'Notice'; case E_CORE_ERROR: return 'Core Error'; case E_CORE_WARNING: return 'Core Warning'; case E_COMPILE_ERROR: return 'Compile Error'; case E_COMPILE_WARNING: return 'Compile Warning'; case E_USER_ERROR: return 'User Error'; case E_USER_WARNING: return 'User Warning'; case E_USER_NOTICE: return 'User Notice'; case E_STRICT: return 'Strict'; case E_RECOVERABLE_ERROR: return 'Recoverable Error'; case E_DEPRECATED: return 'Deprecated'; case E_USER_DEPRECATED: return 'User Deprecated'; default: return 'Unknown Error'; } } /** * Check if error is critical (will stop the system from working) */ private function isCriticalError($errno) { return in_array($errno, array( E_ERROR, // Fatal runtime errors E_PARSE, // Parse errors E_CORE_ERROR, // Fatal errors during PHP startup E_COMPILE_ERROR, // Fatal compile-time errors E_USER_ERROR // User-generated fatal errors )); } /** * Log error to file and database */ private function logError($errorData) { // Log to file $logEntry = sprintf( "[%s] %s: %s in %s on line %d\n Trace: %s", $errorData['timestamp'], $errorData['type'], $errorData['message'], $errorData['file'], $errorData['line'], $errorData['trace'] ?? '' ); try { error_log($logEntry, 3, $this->logFile); } catch (Throwable $e) { error_log('Failed to write CESA error.log: ' . $e->getMessage()); } if ($this->emailNotifications) { try { $this->sendErrorNotification($errorData); } catch (Throwable $e) { error_log('Failed to send error notification email: ' . $e->getMessage()); } } try { $this->logToDatabase($errorData); } catch (Throwable $e) { $this->skipDatabaseLogging = true; error_log('Failed to log error to database: ' . $e->getMessage()); } } /** * True when $db is a mysqli connection that can still run queries. * A closed mysqli object is still truthy; prepare() then throws Error in PHP 8+. */ private function isOpenMysqli($db) { if (!($db instanceof mysqli)) { return false; } try { return $db->thread_id > 0; } catch (Throwable $e) { return false; } } /** * Log error to database */ private function logToDatabase($errorData) { if ($this->skipDatabaseLogging) { return; } try { global $conni, $conn; $db = null; if (isset($conni) && $this->isOpenMysqli($conni)) { $db = $conni; } elseif (isset($conn) && $this->isOpenMysqli($conn)) { $db = $conn; } if (!$db) { return; } $sql = "INSERT INTO error_logs (error_type, error_message, error_file, error_line, error_trace, url, ip_address, user_agent, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())"; $stmt = $db->prepare($sql); if (!$stmt) { return; } $errorType = $errorData['type']; $errorMessage = $errorData['message']; $errorFile = $errorData['file']; $errorLine = $errorData['line']; $errorTrace = $errorData['trace'] ?? ''; $errorUrl = $errorData['url']; $errorIp = $errorData['ip']; $errorUserAgent = $errorData['user_agent']; $stmt->bind_param( 'sssissss', $errorType, $errorMessage, $errorFile, $errorLine, $errorTrace, $errorUrl, $errorIp, $errorUserAgent ); $stmt->execute(); } catch (Throwable $e) { $this->skipDatabaseLogging = true; error_log("Failed to log error to database: " . $e->getMessage(), 3, $this->logFile); } } /** * Send email notification for critical errors */ private function sendErrorNotification($errorData) { $isCli = php_sapi_name() === 'cli'; $subject = $isCli ? "CESA CLI Error: {$errorData['type']}" : "CESA Site Error: {$errorData['type']}"; $message = $isCli ? "A critical error has occurred in a CLI script:\n\n" : "A critical error has occurred on the CESA website:\n\n"; $message .= "Error Type: {$errorData['type']}\n"; $message .= "Message: {$errorData['message']}\n"; $message .= "File: {$errorData['file']}\n"; $message .= "Line: {$errorData['line']}\n"; if (!$isCli) { $message .= "URL: {$errorData['url']}\n"; $message .= "IP: {$errorData['ip']}\n"; } $message .= "Time: {$errorData['timestamp']}\n"; if (isset($errorData['trace'])) { $message .= "\nStack Trace:\n{$errorData['trace']}\n"; } $headers = "From: CESA Systems <noreply@cesa.co.za>\r\nContent-Type: text/plain; charset=UTF-8"; $mailSent = false; if (function_exists('maill')) { try { maill( $this->adminEmail, $subject, $message, null, [ 'isHTML' => false, 'error_mail' => true, 'from-name' => 'CESA Systems' ] ); $mailSent = true; } catch (Throwable $e) { error_log("maill() failed for error notification: " . $e->getMessage(), 3, $this->logFile); } } if (!$mailSent) { try { mail($this->adminEmail, $subject, $message, $headers); } catch (Throwable $e) { error_log("Failed to send error notification email: " . $e->getMessage(), 3, $this->logFile); } } } /** * Display error page for critical errors */ private function displayErrorPage($errorData) { // Clear any output buffers while (ob_get_level()) { ob_end_clean(); } // Check if running in CLI mode if (php_sapi_name() === 'cli') { $this->displayCliError($errorData); exit; } // Set appropriate HTTP status code http_response_code(500); // Set content type header('Content-Type: text/html; charset=UTF-8'); // Display custom error page $this->renderErrorPage($errorData); exit; } /** * Display error in CLI mode */ private function displayCliError($errorData) { echo "\n"; echo "╔══════════════════════════════════════════════════════════════════════════════╗\n"; echo "║ SYSTEM ERROR ║\n"; echo "╚══════════════════════════════════════════════════════════════════════════════╝\n\n"; echo "Error Type: " . $errorData['type'] . "\n"; echo "Message: " . $errorData['message'] . "\n"; echo "File: " . $errorData['file'] . "\n"; echo "Line: " . $errorData['line'] . "\n"; echo "Time: " . $errorData['timestamp'] . "\n"; if (isset($errorData['url']) && $errorData['url'] !== 'CLI') { echo "URL: " . $errorData['url'] . "\n"; } if (isset($errorData['ip']) && $errorData['ip'] !== 'CLI') { echo "IP: " . $errorData['ip'] . "\n"; } if (isset($errorData['trace'])) { echo "\n"; echo "╔══════════════════════════════════════════════════════════════════════════════╗\n"; echo "║ STACK TRACE ║\n"; echo "╚══════════════════════════════════════════════════════════════════════════════╝\n"; echo $errorData['trace'] . "\n"; } echo "\n"; echo "╔══════════════════════════════════════════════════════════════════════════════╗\n"; echo "║ END OF ERROR REPORT ║\n"; echo "╚══════════════════════════════════════════════════════════════════════════════╝\n\n"; } /** * Display error in development mode */ private function displayError($errorData) { echo "<div style='background: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; padding: 10px; margin: 10px; border-radius: 4px;'>"; echo "<strong>{$errorData['type']}:</strong> {$errorData['message']}<br>"; echo "<strong>File:</strong> {$errorData['file']}<br>"; echo "<strong>Line:</strong> {$errorData['line']}<br>"; echo "<strong>Time:</strong> {$errorData['timestamp']}<br>"; echo "</div>"; } /** * Render custom error page */ private function renderErrorPage($errorData) { ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>System Error - CESA</title> <style> body { font-family: Arial, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); margin: 0; padding: 0; min-height: 100vh; display: flex; align-items: center; justify-content: center; } .error-container { background: white; border-radius: 10px; box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1); padding: 40px; max-width: 900px; width: 90%; text-align: center; } .error-icon { font-size: 64px; color: #e74c3c; margin-bottom: 20px; } .error-title { color: #2c3e50; font-size: 28px; margin-bottom: 15px; font-weight: bold; } .error-message { color: #7f8c8d; font-size: 16px; line-height: 1.6; margin-bottom: 30px; } .error-details { background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 5px; padding: 20px; margin: 20px 0; text-align: left; font-family: 'Courier New', monospace; font-size: 12px; color: #495057; display: block; overflow: auto; } .error-details pre { white-space: pre-wrap; word-break: break-word; margin: 8px 0 0; } .error-id { background: #e9ecef; padding: 5px 10px; border-radius: 3px; font-family: monospace; font-size: 12px; color: #495057; margin-top: 20px; } .back-button { background: #3498db; color: white; padding: 12px 24px; border: none; border-radius: 5px; text-decoration: none; display: inline-block; margin-top: 20px; transition: background 0.3s; } .back-button:hover { background: #2980b9; } .contact-info { margin-top: 30px; padding-top: 20px; border-top: 1px solid #e9ecef; color: #7f8c8d; font-size: 14px; } </style> </head> <body> <div class="error-container"> <div class="error-icon">⚠️</div> <h1 class="error-title">System Error</h1> <p class="error-message"> We're sorry, but something went wrong on our end. Our technical team has been notified and is working to resolve the issue. </p> <div class="error-details"> <strong>Error Type:</strong> <?php echo htmlspecialchars((string) ($errorData['type'] ?? '')); ?><br> <strong>Message:</strong> <?php echo htmlspecialchars((string) ($errorData['message'] ?? '')); ?><br> <strong>File:</strong> <?php echo htmlspecialchars((string) ($errorData['file'] ?? '')); ?><br> <strong>Line:</strong> <?php echo htmlspecialchars((string) ($errorData['line'] ?? '')); ?><br> <strong>URL:</strong> <?php echo htmlspecialchars((string) ($errorData['url'] ?? '')); ?><br> <strong>Time:</strong> <?php echo htmlspecialchars((string) ($errorData['timestamp'] ?? '')); ?><br> <strong>Stack Trace:</strong> <pre><?php echo htmlspecialchars((string) ($errorData['trace'] ?? '(no stack trace)')); ?></pre> </div> <a href="/" class="back-button" onclick="history.back(); return false;">Go back and try again</a> <a href="/" class="back-button">Return to Homepage</a> <div class="contact-info"> <p>If this problem persists, please contact our support team at <a href="mailto:info@cesa.co.za">info@cesa.co.za</a></p> </div> </div> </body> </html> <?php } } // Initialize the error handler CESAErrorHandler::getInstance(); // Create error_logs table if it doesn't exist function createErrorLogsTable() { try { global $conni, $conn; $db = null; if (isset($conni) && $conni) { $db = $conni; } elseif (isset($conn) && $conn) { $db = $conn; } $mysqliOpen = false; if ($db instanceof mysqli) { try { $mysqliOpen = $db->thread_id > 0; } catch (Throwable $e) { $mysqliOpen = false; } } if (!$mysqliOpen) { return; } $sql = "CREATE TABLE IF NOT EXISTS error_logs ( id INT AUTO_INCREMENT PRIMARY KEY, error_type VARCHAR(50) NOT NULL, error_message TEXT NOT NULL, error_file VARCHAR(255) NOT NULL, error_line INT NOT NULL, error_trace TEXT, url VARCHAR(500), ip_address VARCHAR(45), user_agent TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, INDEX idx_error_type (error_type), INDEX idx_created_at (created_at) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; $db->query($sql); } catch (Throwable $e) { // Silently fail - table creation is not critical } } // Create the table when this file is included createErrorLogsTable();