What role does output buffering play in preventing header errors when setting cookies in PHP?

Output buffering plays a crucial role in preventing header errors when setting cookies in PHP because it allows headers to be sent only when the entire page has been generated. This prevents any output, including whitespace, from being sent before headers are set, which can cause errors when trying to set cookies.

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

// Set cookie
setcookie("user", "John Doe", time() + 3600, "/");

ob_end_flush(); // Flush the output buffer
?>