Skip to content
Advertisement

Why do PHP headers never go in the body?

Why is it that PHP headers never go in the body? Or why do we never even leave a line before when we include the php code to do a redirection using the header? For reference:

<php
    header("Location:https://stackoverflow.com");
?>

<!DOCTYPE html>
.
.
.
.

Advertisement

Answer

In the http request and response cycle the user sends the request and henceforth the server sends the response by sending the requested web page (it sends additional information too!), the way the page is sent is as follows;

http/version       status code      

-------------------------------

Name1 : Value1
Name2 : Value2
Name3 : Value3

-------------------------------

File Requested



Eg of response message:

HTTP/1.0 200:OK

--------------------------------

Host: www.mywebsite.com
Accept-language:en-us
Accept: text/html


--------------------------------

products/myproduct.html

*The dotted lines are added for reference only!

The mid section of the message (between 2nd and 3rd dotted lines) are where the headers MUST lie. The webserver parses the file requested and as soon as it comes across any content eg: Whitespace before <!DOCTYPE html> or the file content itself, it sends these headers. So in the case that you want to send a header inside the file itself,it would result in an error that goes along the words: Headers already sent , because as I said the headers are sent as soon as any content is encountered! So you cannot send any headers after that! Hence the solution is to send the headers before any HTML is encountered. So it must be before <!DOCTYPE html>, but again no whitespace is allowed since it is counted as content!

Solution:

<?php

header("Location:https://stackoverflow.com");




?>
<!DOCTYPE html>
.
.
.
.
.

Keep in mind, any whitespace INSIDE the php tags is perfectly fine!

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement