0
0
PhpDebug / FixBeginner · 3 min read

How to Fix Maximum Execution Time Exceeded in PHP

The maximum execution time exceeded error in PHP happens when a script runs longer than the allowed time. You can fix it by increasing the time limit using set_time_limit() or ini_set('max_execution_time'), or by optimizing your code to run faster.
🔍

Why This Happens

This error occurs because PHP stops a script that runs longer than the set maximum execution time to prevent server overload. If your code has a long loop or slow process, PHP will throw this error.

php
<?php
// Example of code causing maximum execution time exceeded error
while (true) {
    // Infinite loop
}
?>
Output
Fatal error: Maximum execution time of 30 seconds exceeded in /path/to/script.php on line 3
🔧

The Fix

You can fix this by increasing the allowed execution time with set_time_limit() or ini_set(). This tells PHP to allow the script to run longer. Alternatively, optimize your code to avoid infinite loops or heavy processing.

php
<?php
// Increase max execution time to 60 seconds
set_time_limit(60);

// Or using ini_set
// ini_set('max_execution_time', '60');

// Example of a loop that now runs safely
for ($i = 0; $i < 1000000; $i++) {
    // Some processing
}

echo "Script completed successfully.";
?>
Output
Script completed successfully.
🛡️

Prevention

To avoid this error in the future, write efficient code that does not run unnecessary loops or heavy tasks. Use functions like set_time_limit() wisely and avoid infinite loops. Also, test scripts with large data to check performance before deployment.

⚠️

Related Errors

Similar errors include memory limit exceeded, which happens when your script uses too much memory. You can fix it by increasing memory_limit in php.ini or optimizing memory usage. Another related error is timeout in database queries, which requires optimizing queries or increasing timeout settings.

Key Takeaways

Increase PHP execution time with set_time_limit() or ini_set('max_execution_time') to fix the error.
Avoid infinite loops and optimize code to prevent long-running scripts.
Test scripts with large data sets to catch performance issues early.
Be aware of related errors like memory limit exceeded and optimize accordingly.