[Tutor] Newbie: CGI

Magnus Lyckå magnus@thinkware.se
Tue Apr 29 05:51:02 2003


Selamat Datang Mico,

At 14:53 2003-04-29 +0700, Mico Siahaan wrote:
>  I tried to make a simple CGI script with python.
>
>But I got this error: (copied from Apache's log):
>[error] [client 202.146.238.5] malformed header from script. Bad
>header=PIPELINING: /var/www/html/sites/ullysigar/cgi-bin/ullyform.cgi
>
>What does this error mean? And how to correct it?

It's much easier to debug programs if we can see the code. :)

When you run into a problem, it's a good thing to try to
reduce the problem. Try do construct a really small program
that exhibits that error.

Having said that, I can tell you about this one...

Each CGI program must first present a header, which describes
the content of the data to come. A naive CGI script like this...

#!/usr/bin/env python -u
print "<html>Hello World</html>"

...will not work. It will actually assume that the first line(s)
contain the header, and it obviously won't recognize that string
of HTML as a proper header. Thus the error message: Malformed header.

See http://www.ietf.org/rfc/rfc2068.txt

    Both types of message[*] consist of a start-line, one
    or more header fields (also known as "headers"), an empty line (i.e.,
    a line with nothing preceding the CRLF) indicating the end of the
    header fields, and an optional message-body.

[*] Request and response

How these headers look is defined in the MIME standards (RFC2045-2047),
and the registered types are shown 
inftp://ftp.isi.edu/in-notes/iana/assignments/media-types/media-types

So, lets add an appropriate header and an empty line, and see what happens:

#!/usr/bin/python -u
print "Content-type: text/html"
print
print "<html>Hello World</html>"

Does it work now? Remember that you must always print an empty
line between the header and the page content. The header might
consist of more than one line, and the empty line acts as the
separator.

In this case, with content starting with <html>, the browsers I
checked will actually display HTML regardless of what content-type
you set, but the following two examples will display differently.

#!/usr/bin/python -u
print "Content-type: text/html"
print
print "Hello <b>World</b>!"

#!/usr/bin/python -u
print "Content-type: text/plain"
print
print "Hello <b>World</b>!"

See?


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program