This wouldn't be a problem with the script since it runs fine from the command but a misconfiguration of apache or whatever webserver you are using.
I missed your post somehow so I realize this is a late reply. The problem could very well be the script. If run as a CGI it needs to print an http header before trying to print anything else. This is not a problem from the command line and will work, but will error out with a 500 ISE if initiated as a CGI script from a browser.