Avoid Exit Die
ID |
php.avoid_exit_die |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Php |
Tags |
control-flow, reliability |
Description
Reports use of the exit and die language constructs (with or without an argument:
exit;, exit(1);, die;, die('message');). Both immediately terminate the running PHP
process.
Rationale
die is an alias of exit; both end script execution on the spot. Using them for error
handling is harmful in any code that is not a throwaway script: a halted process cannot run
registered shutdown handlers in a controlled way, cannot return a meaningful response to a
web client, and cannot be unit-tested (the test runner is killed too). They also bypass the
exception mechanism, so callers get no chance to recover, retry or translate the failure
into a proper HTTP status or log entry.
<?php
if (!isset($request['id'])) {
exit; // FLAW — kills the whole request, no response, no cleanup
}
if ($token === 'bad') {
die('forbidden'); // FLAW — same problem, alias of exit
}
if (!isset($request['id'])) {
throw new InvalidArgumentException('missing id'); // OK — caller can catch and respond
}
return (int) $request['id']; // OK — return a value to the caller
Remediation
Replace exit/die with an exception (throw new RuntimeException(…)) or a normal
return, and let the framework or entry point decide how to respond and clean up. Reserve
process termination for genuine top-level scripts, where it should be a single,
clearly-documented exit at the end of main-style code rather than scattered through the
logic.