I’m having a lot of trouble getting my Perl CGI script to render HTML. It keeps outputting HTML as plain text. I even tried explicitly setting the Content-Type with print header("text/html");
Is there anything wrong with the following code? –
use CGI qw(:standard);
# other code
print header("text/html");
# also tried just print header;
my $banner = "Some text";
print start_html($banner);
print h3($banner);
print start_form(-method=>"POST");
# HTML form specific code
print end_form;
print end_html;
When I check Elements tab on Chrome’s Developer’s tools, for some reason the entire HTML is wrapped inside a <pre>
tag which is in turn inside another HTML document. So the HTML is malformed but I’m unable to understand why –
<html>
<head></head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;"><!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
<head>
<title>Some text</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<h3>Some text</h3><form method="post" action="/path/script.pl?param1=val1¶m2=val2" enctype="multipart/form-data">
//form specific code
</form>
</body>
</html></pre>
</body>
</html>
Any help would be greatly appreciated.
3
Answers
Try this:
print(header(-type => 'text/html'));
at least that worked for me.
Yes. It doesn’t even compile, for starters.
But after changing all
//
to#
, we get a perfectly fine program that doesn’t output any PRE elements.When I run your program, I get the following output:
Which is exactly what I’d expect to see and nothing like what you are seeing. I can see two possibilities to explain this discrepancy:
# other code
section of your program which is outputting a set of CGI headers (and, perhaps, the<pre>
tags as well).An easy way to differentiate between these two cases would be to run your program from the command line and see what output you get. If you get your output, then the problem is somewhere in the
# other code
, if you get my output, then the problem is in the web server configuration.As an aside, I’d highly recommend that you read the section entitled HTML Generation functions should no longer be used in a recent version of the CGI module documentation and the CGI::Alternatives page to see some suggestions for better approaches.