How can using PHP code before HTML code prevent header modification errors in web applications?

When PHP code is executed before any HTML output, it ensures that no headers have been sent to the browser yet. This prevents header modification errors that may occur if headers are sent after HTML content. To avoid these errors, it is recommended to place all PHP code at the beginning of the file, before any HTML code.

<?php
// Start the PHP session
session_start();

// Perform any necessary PHP operations here

// Output HTML content below
?>
<!DOCTYPE html>
<html>
<head>
    <title>Example Page</title>
</head>
<body>
    <h1>Hello, World!</h1>
</body>
</html>