php – Cannot modify header information – headers already sent by (php header already sent error)

This error comes when you print any thing before php hreader command or sometime single spaces allowed before any file starting place or printing or getting values from $_COOKIE or $_SESSION or set cookie or set session etc…

Example Error Code:
<?php
print “text”;
header(‘Location: http://www.example.com/’);
?>

Solution :

<?php
function JSRedirection($url)
{?>
<script type=”text/javascript”>
<!–
window.location = “<?=$url?>”
//–>
</script>
<?}
print “test”;
JSRedirection(“http://www.example.com/”);

?>

Above is by use of js redirect function. But we can solved it by php functions only.

Example 1:

<?php
header("location: 1.html");
header("location: 2.html"); //replaces 1.html
?>

This redirects to 2.html since the second header replaces the first.

Example 2:

<?php
header("location: 1.html");
echo "send data";
header("location: 2.html"); //1.html already sent
?>

This redirects to 1.html since the header is sent as soon as the echo happens. You also won't see any "headers already sent" errors because the browser follows the redirect before it can display the error.

Example 3:

<?php
ob_start();
header("location: 1.html");
echo "send data";
header("location: 2.html"); //replaces 1.html
ob_end_flush(); //now the headers are sent
?>

Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren't sent until the output buffer is flushed.

OR

Need to write <?php ob_start(); ?> at first line of html part when you main body is common for all pages.

like:

<?php ob_start(); ?>

<html> ……  <?php include_once “<included part of files >”;  ?>  …… </html>