Skip to content
PHP Logo

What is the issue with using header() function for redirection in PHP?

The issue with using the header() function for redirection in PHP is that it must be called before any output is sent to the browser. If there is any output (such as HTML, whitespace, or error messages) before the header() function is called, it will result in a "headers already sent" error. To solve this issue, you can use output buffering to capture all output before sending it to the browser.

php
<?php
ob_start(); // Start output buffering

// Your PHP code here

// Redirect to a new page
header('Location: newpage.php');

ob_end_flush(); // Flush the output buffer and send it to the browser
exit; // Stop further execution of the script
?>