What are some alternative approaches or solutions to redirecting users after successful login in PHP to avoid the header modification error?

When redirecting users after successful login in PHP, the header modification error can occur if any output has been sent to the browser before the header() function is called. To avoid this error, one solution is to use output buffering to capture any output before sending headers.

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

// Your login logic here

if ($login_successful) {
    ob_end_clean(); // Clean the output buffer
    header("Location: dashboard.php"); // Redirect to dashboard page
    exit();
} else {
    ob_end_flush(); // Flush the output buffer
    // Display error message or login form
}
?>