the windows/unix is clearly newlines .. be sure to convert properly (it might be your ftp client, too--make sure it's doing ascii mode)
You don't have to have the whole thing inside of a here-doc
the internal server error is likely (if it's not the next item) due to lack of headers. What is in the web server's error_log? when run on cmd line, what is the exact output?
(this could also be the server error) You shouldn't be exit'ing a cgi program like that... just remove that line. the web server might be server erroring because of that return code.