What role does the headers_sent() function play in setting the Content-Type header for file downloads in PHP?

The headers_sent() function in PHP is used to check if any headers have already been sent to the browser. When setting the Content-Type header for file downloads, it is important to ensure that no headers have been sent before setting the header to avoid any errors. By using the headers_sent() function, we can check if headers have been sent and then set the Content-Type header accordingly.

if (!headers_sent()) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="example.txt"');
    readfile('example.txt');
    exit;
} else {
    echo "Headers have already been sent. Cannot set Content-Type header.";
}