I'm not sure why your code behaves this way when executed as a CGI script (I'd want to see more of the code to figure that out), but I will point out that you are not using the right content-type. You're printing a content-type of text/html, when your content is actually text/plain.