What are common pitfalls when using the header() function in PHP and how can they be avoided?

Common pitfalls when using the header() function in PHP include sending headers after content has already been output, not properly handling error conditions, and not sanitizing user input before using it in headers. These issues can be avoided by ensuring that headers are sent before any content, checking for errors when setting headers, and validating and sanitizing user input.

// Avoid sending headers after content
ob_start(); // Start output buffering
// Your PHP code here
header('Location: https://www.example.com');
ob_end_flush(); // Flush output buffer

// Proper error handling for setting headers
if (!headers_sent()) {
    header('Content-Type: text/html');
} else {
    // Handle error condition
    echo "Error: Headers already sent";
}

// Sanitize user input before using in headers
$user_input = $_GET['input'];
$sanitized_input = htmlspecialchars($user_input);
header('X-User-Input: ' . $sanitized_input);