max_execution_time & set_time_limit()
TL;DR
max_execution_time limits script CPU time (not wall-clock time) — use set_time_limit(0) sparingly for long-running CLI tasks, never for web requests.
Explanation
max_execution_time (default 30s) measures CPU time consumed by the PHP process, not wall-clock time. Blocking I/O (sleep, DB queries, HTTP requests) does NOT count. This means a script making many slow DB calls can run for minutes without hitting the limit. set_time_limit(N) resets the timer from the current point. CLI scripts have max_execution_time=0 (unlimited) by default. The fatal error it produces is uncatchable. For long operations: use background jobs/queues, call set_time_limit() in loops, or use CLI with time limits managed by the OS.
Common Misconception
✗ max_execution_time is wall-clock time — it only counts CPU time. A script sleeping or waiting for I/O can run indefinitely regardless of the setting.
Why It Matters
Runaway scripts consuming CPU without hitting time limits can starve servers. Conversely, legitimate long-running imports may need explicit set_time_limit() calls.
Common Mistakes
- Using set_time_limit(0) in web requests — allows infinite execution.
- Assuming max_execution_time protects against slow DB queries.
- Not using background jobs for operations known to exceed 30s.
Code Examples
✗ Vulnerable
// In a web controller:
set_time_limit(0); // Disable limit for 'safety'
foreach ($millionRows as $row) { processRow($row); }
✓ Fixed
// In a CLI command or queue worker:
set_time_limit(3600); // 1 hour for this operation
// Reset per chunk to avoid single-chunk timeout:
foreach (array_chunk($rows, 500) as $chunk) {
set_time_limit(60); // 60s per chunk
processChunk($chunk);
}
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
22 Mar 2026
Views
23
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 1
No pings yesterday
Perplexity 7
Amazonbot 6
Unknown AI 3
Google 2
ChatGPT 1
Ahrefs 1
Also referenced
How they use it
crawler 17
crawler_json 1
pre-tracking 2
Related categories
⚡
DEV INTEL
Tools & Severity
🟡 Medium
⚙ Fix effort: Medium
⚡ Quick Fix
Move long operations to CLI/queue workers. In loops, call set_time_limit(60) per iteration. Never use set_time_limit(0) in web request handlers.
📦 Applies To
PHP 4.0+
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
set_time_limit(0)
Auto-detectable:
✓ Yes
phpcs
phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: High
False Positives: Low
✗ Manual fix
Fix: Medium
Context: Function
CWE-400