Wednesday, 16 January 2013

PHP : Warning: Cannot modify header information - headers already sent




Consider the following code segment :-

<!DOCTYPE html>
<html>
<head>
<title>
Headers
</title>
</head>
<script>
.
.  /*Your scripts here*/
.
</script>
<?php
.
. /*some code*/
header ('Location: http://www.mysite.com/');
?>


The given code will give you an error , stating that headers were already sent

Why ??

Headers are normally sent before a session is started . Here before the php code , we already have something which the client side browser will render , and so headers will already be sent . Even if there is nothing but a whitespace , then also we'll have a similar error.

Solution !!

Place the php script containing the header at the beginning of the php file . That'll settle all issues !! Remember there shouldn't even be any white spaces before the opening <?php tag .

 --------------------------------------------------------------------------------------
<?php
.
. /*some code*/
header ('Location: http://www.mysite.com/');
?>
<!DOCTYPE html>
<html>
<head>
<title>
Headers
</title>
</head>
<script>
.
.  /*Your scripts here*/
.
</script>



No comments:

Post a Comment