QA
Beginner LevelPHP 8+

Why does calling header("Location: ...") throw "Headers already sent" and how does Output Buffering (ob_start) fix it?

❓ Interview Prompt: Explain the "Cannot modify header information - headers already sent" error, HTTP protocol response structure, and Output Buffering (ob_start).

In the HTTP protocol, response headers MUST be sent before the response body content.

Why "Headers Already Sent" Occurs:

If your script echoes even a single space character, HTML tag, or UTF-8 BOM before calling 'header()', PHP automatically flushes HTTP headers and starts sending body content. Calling 'header("Location: ...")' afterwards throws a fatal error!

Solution - Output Buffering ('ob_start()'):

Output Buffering holds all echoed body content in server RAM instead of sending it directly to the browser. This allows calling 'header()' anywhere in your code. The buffer is flushed to the browser at script completion.

Code Implementation Example

php
<?php
// Enable Output Buffering at script start
ob_start();

echo "<html><body>Some body text echoed early</body></html>";

// Calling header redirect after echo works because Output Buffering is active!
if (!isset($_SESSION['user'])) {
    header("Location: /login.php");
    exit(); // Always exit after redirect headers!
}

// Flush output buffer to browser
ob_end_flush();
💡Preventing "Headers already sent" errors using Output Buffering.
🎯 Interview Key Takeaway

HTTP response headers must precede body content. Use ob_start() Output Buffering to buffer content in RAM and prevent header errors.

#header#Output Buffering#HTTP#Beginner
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?