PHP - exit or return which is better?

PHP - exit or return which is better?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

exit vs return: The Critical Distinction in PHP Error Handling

When handling large files in a web application, performance and resource management are non-negotiable. If you detect that $fileSize exceeds a safe threshold, such as 100 units, stopping the script immediately is often the correct architectural decision to prevent server overload or memory exhaustion. However, how you signal this failure to the client matters significantly. The choice between using exit(), passing data to exit(), or using return() changes not just the flow of execution, but the fate of your HTTP response headers and output buffers.

Case I: The Standard Termination

The first pattern uses exit() without arguments after echoing a JSON message. This is functionally equivalent to calling die(). When you execute this line, PHP immediately halts script execution. Crucially, this prevents any subsequent code from running, ensuring that heavy file processing logic doesn't continue in the background.

However, there is a distinct downside here regarding HTTP semantics. By calling echo followed by exit(), you are manually writing to the output buffer. If your application framework or middleware expects to manage headers (like setting a custom error code or adding CORS headers) after this point, they will fail because the headers have already been sent and the script has stopped. Furthermore, if an exception is thrown later in the stack trace that you intended to catch globally, it will never be caught because the process has already terminated.

Case II: Passing Data to exit()

The second approach attempts to pass the encoded JSON string directly into exit(): exit( json_encode( $results ) );. While this might look like a neat shortcut, it is technically incorrect for standard HTTP responses. The exit() function (and its alias die()) expects a boolean argument or an integer status code representing the exit status of the shell process.

When you pass a string to exit(), PHP does not treat that string as the content of the HTTP response body. Instead, it treats the string as an error message to be displayed if the script exits with an error state, or it may simply ignore the argument depending on the version and configuration. Consequently, your JSON payload will likely not appear in the browser's response body as intended. You are effectively discarding the data you just encoded, making this pattern unreliable for API responses.

Case III: The Return Pattern

The third option involves using return( json_encode( $results ) );. This is the only pattern among the three that correctly returns a value from the function or scope where it resides. However, its utility depends entirely on the context of execution. If this code block exists within a function, return stops the function and passes the JSON string back to the caller. The calling code can then decide whether to echo that string or handle it differently.

If this logic sits in the global scope (the root of your script), return behaves similarly to exit(), but with a critical difference: it returns a value. In modern PHP versions, when return is used at the top level, the returned value becomes the output if no headers have been sent yet, and then the script terminates. This mimics the desired behavior of sending data and stopping execution without manually calling echo.

The Verdict for API Development

For building APIs where you need to send a JSON payload before terminating, Case III is the most robust option. It allows your framework or wrapper function to handle the output buffering and header setting consistently. For example, if you wrap this logic in a controller method, you can use return to signal success or failure to the routing layer, which then formats the final response.

function validateFileSize($fileSize) {
    if ($fileSize > 100) {
        $results['msg'] = 'fileSize is too big!';
        // Return allows the caller to handle output and headers
        return json_encode($results); 
    }
    return null; // Or continue processing
}

// In your controller:
$output = validateFileSize($fileSize);
if ($output !== null) {
    echo $output; // Explicitly echo the result
    exit(); // Ensure no further code runs
}

Using return provides a clear separation between business logic (checking size) and presentation logic (sending headers and echoing). It avoids the pitfalls of exit() swallowing your data payload while maintaining strict control over when the script actually halts. For large-scale file handling, ensuring that the server stops processing immediately is vital; any pattern that relies on implicit behavior should be scrutinized to ensure no background jobs or cleanup routines are skipped unintentionally.

Our network