1. <?php
  2. /**
  3. * Cleans the runtime environment for scheduled runs, with fallback logic.
  4. *
  5. * @return bool True on success, false on failure.
  6. */
  7. function cleanRuntimeEnvironment(): bool
  8. {
  9. // Attempt to clear the opcache.
  10. if (opcache_reset() === false) {
  11. error_log("Failed to clear opcache: " . error_get_last()['message']);
  12. // Fallback: Try unloading all functions.
  13. unload_all_functions();
  14. if (opcache_reset() === false) {
  15. error_log("Failed to clear opcache after unloading functions: " . error_get_last()['message']);
  16. return false; //Final fallback failure
  17. }
  18. }
  19. // Unload all functions to ensure a clean state.
  20. unload_all_functions();
  21. // Clear the autoloader.
  22. spl_autoload_register(null);
  23. //Clear session data.
  24. session_unset();
  25. session_destroy();
  26. //Clear the error log
  27. if (file_put_contents('php_error.log', '') === false) {
  28. error_log("Failed to clear php_error.log: " . error_get_last()['message']);
  29. }
  30. return true;
  31. }
  32. /**
  33. * Unloads all functions.
  34. */
  35. function unload_all_functions(): void
  36. {
  37. $functions = get_declared_functions();
  38. foreach ($functions as $function) {
  39. if (function_exists($function)) {
  40. unload_function($function);
  41. }
  42. }
  43. }
  44. /**
  45. * Unloads a single function.
  46. *
  47. * @param string $function The name of the function to unload.
  48. */
  49. function unload_function(string $function): void
  50. {
  51. if (unload_function_by_name($function) === false) {
  52. error_log("Failed to unload function: " . $function);
  53. }
  54. }
  55. /**
  56. * Unloads a function by name.
  57. * @param string $functionName
  58. * @return bool
  59. */
  60. function unload_function_by_name(string $functionName): bool
  61. {
  62. $result = @unload_function($functionName);
  63. if ($result === false) {
  64. return false;
  65. }
  66. return true;
  67. }
  68. ?>

Add your comment