What are the best practices for handling session initialization and registration in PHP to avoid header-related issues?

When handling session initialization and registration in PHP, it's important to make sure that session-related functions are called before any output is sent to the browser to avoid header-related issues. To do this, you can use the session_start() function at the beginning of your script to initialize the session and handle registration.

<?php
session_start();

// Check if the user is already logged in
if(isset($_SESSION['logged_in'])) {
    // Redirect to the dashboard or home page
    header("Location: dashboard.php");
    exit();
}

// Handle registration form submission
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register'])) {
    // Process registration data
    // Set session variables
    $_SESSION['logged_in'] = true;
    
    // Redirect to the dashboard or home page
    header("Location: dashboard.php");
    exit();
}
?>