1. <?php
  2. /**
  3. * Gracefully handles runtime environment fallback and diagnostics with error logging.
  4. */
  5. // Define fallback environment variables and their defaults.
  6. $fallback_env = [
  7. 'DEBUG' => false,
  8. 'LOG_DIR' => 'logs',
  9. 'ENVIRONMENT' => 'fallback',
  10. ];
  11. // Merge environment variables with defaults.
  12. $_ENV = array_merge($_ENV, $fallback_env);
  13. // Error logging function.
  14. function logError($message) {
  15. global $LOG_DIR;
  16. $timestamp = date('Y-m-d H:i:s');
  17. $logFile = $LOG_DIR . '/' . $timestamp . '.log';
  18. error_log("[$timestamp] ERROR: $message", 3, $logFile); // Log to file
  19. error_log("[$timestamp] ERROR: $message", 3, null); //Also send to standard error stream
  20. }
  21. // Check for environment variables.
  22. if (!isset($_ENV['DEBUG'])) {
  23. $_ENV['DEBUG'] = false; //Default to false if not set
  24. }
  25. if (!isset($_ENV['LOG_DIR'])) {
  26. $_ENV['LOG_DIR'] = 'logs'; //Default log directory
  27. }
  28. if (!isset($_ENV['ENVIRONMENT'])) {
  29. $_ENV['ENVIRONMENT'] = 'fallback'; //Default environment
  30. }
  31. // Diagnostic logging
  32. if ($_ENV['DEBUG']) {
  33. // Log basic environment information.
  34. logError("--- Environment Diagnostics ---");
  35. logError("DEBUG: Environment: " . $_ENV['ENVIRONMENT']);
  36. logError("DEBUG: Debug Mode: " . $_ENV['DEBUG']);
  37. logError("DEBUG: Log Directory: " . $_ENV['LOG_DIR']);
  38. logError("DEBUG: PHP Version: " . phpversion());
  39. logError("DEBUG: Server OS: " . PHP_OS);
  40. logError("DEBUG: Server Architecture: " . PHP_SAPI);
  41. //Example of checking if a specific function exists
  42. if(function_exists('mysqli_connect')){
  43. logError("DEBUG: mysqli_connect function available.");
  44. } else {
  45. logError("DEBUG: mysqli_connect function NOT available.");
  46. }
  47. }
  48. //Example usage: Implement your application logic here.
  49. //If certain features require a specific environment, you can check $_ENV['ENVIRONMENT'] and handle accordingly.
  50. ?>

Add your comment