in reply to Malformed header error

You could try running the script from the command line and having a look at the headers it produces, I would be willing to bet that it is spitting out something other than a header prior to the header itself and thus causing the error.