Reputation: 5927
In CGI script, on the top the program we use the:
print "Content-type: text/html\n\n";
Without using \n
it will not execute. But, inside the HTML body, we do not use \n
because \n
can't make any sense, for new line we use <br>
tag.
Why \n
is necessary in the header line?
Upvotes: 2
Views: 1399
Reputation: 1701
Note: a "CRLF" is equivalent to "\r\n" (i.e. a carriage return followed by a line feed newline.
For every HTTP message, each Header field must be followed by a CRLF, after which, all of the header fields together, are followed by another CRLF (a blank line), as specified in RFC 2616.
So, you may ask, if two CRLFs are needed following the HTTP headers, why don't we just write CGI scripts with code like:
print "Content-type: text/html\r\n\r\n";
We very well could, such code will run just fine! However, since Unix-based systems like Linux and macOS use a LF for a newline rather than CRLF, CGI servers are tailored to play nice with the Unix environment, and do so by converting each \n
in our CGI Header into a \r\n
HTTP Header, as specified in RFC 3875.
Taking advantage of the LF -> CRLF translation that occurs on the server when a CGI script runs and the CGI headers are translated to HTTP headers, we can run:
print "Content-type: text/html\n\n";
and as long as our CGI server is behaving according to the RFC specifications, those two LF characters will be rendered as two CRLFs when the HTTP message is sent.
With this principle of LF -> CRLF substitution in mind, we can play around with other possibilities, for instance letting the CGI server substitute CRLF for just the first LF:
print "Content-type: text/html\n\r\n";
or just the second LF:
print "Content-type: text/html\r\n\n";
and both will work!
Upvotes: 2
Reputation: 46207
Any HTTP response (regardless of whether the content is HTML or not) must begin with a status code (which is normally added by the web server, not your CGI program), a Content-Type header, and optionally one or more additional headers. Each header must be on a separate line (i.e., terminated with a \n
). After all headers have been sent, a blank line is used to indicate that the headers are complete and the body of the response follows.
After the headers are complete, then the HTML (or other) body begins and \n
no longer has any real meaning, since HTML ignores it when rendering the content.
Upvotes: 1
Reputation: 278
Content-type: text/html
is the HTTP header, not HTML. For detecting the end of HTTP header must be one empty line. First \n
for end of current line, second \n
for new empty line.
Upvotes: 3
Reputation: 4709
The first line of CGI script must be Content-Type: text/html
and the print statement must have 2 \n
characters:
The second to produce the require blank line between CGI header and data.
print "Content-Type: text/html\n\n";
Upvotes: 2