PHP Annoyances: header()
Earlier today, and yesterday in fact, I was successfully downloading generated PDF’s from a FLEX application from an Apache2 server via mod_php5. Tonight however, it kept failing with an IOErrorEvent #2038. There’s lots of fun references to this issue like this one. Sadly downloading via FileReference doesn’t trigger the HTTPStatusEvent event, so I can’t lie to FLEX.
I eventually stopped brute forcing an attempt and intelligently looked at Apache2′s logs and found this wonderful line:
10.10.220.130 – - [10/Feb/2009:20:24:16 -0500] “GET /vrm/Create_Report.php?download=vrm_report_17_10-10-220-130.pdf HTTP/1.1″ 1 68856 “-” “Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; …)”
Do you notice whats wrong? No? Look for the 1 after “HTTP/1.1″ and before the “68856″ – this is where the HTTP Status Code should be. Eh? What happened? Where’d my status go? The server-side looked like this:
if (file_exists($file)) {
header('Content-Type', 'application/octet-stream', true);
header('Content-Disposition', 'attachment/filename=' . $filename, true);
header('Content-Length', filesize($file), true);
header('Content-Description', 'File Transfer');
readfile($file);
}
Any one notice the issue – header is being use inappropriately. The first argument should be the entire response header, the second argument is the option to override a matching header, and the third is the status code. “true” evaluates “1″ and thus the status of 1. You might ask as I am right now: Why is he divulging that he’s an idiot? Well folks it goes like this:
It’s 10:55PM and I’ve been programming since 8:30AM to meet a deadline. Things get missed and stupid mistakes happen. The above code worked on (IIS 6 + PHP5) but failed on (Apache2 + PHP5) – and this is one of the many reasons I hate PHP. The second argument should be a boolean and should SCREAM to the error log if you don’t match the type expected. Instead it says nothing, and leaves you to your madness.
Anyways, lets fix the code and go home!
header('Content-Type: application/octet-stream', true, 200);
header('Content-Disposition: attachment/filename=' . $filename, true);
header('Content-Length: ' . filesize($file), true);
header('Content-Description: File Transfer');
10.10.220.130 – - [10/Feb/2009:22:14:15 -0500] “GET /vrm/Create_Report.php?download=vrm_report_1_10-10-220-130.pdf HTTP/1.1″ 200 68856 “-” “Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; …)”
Gah ;-0
Leave a Reply
You must be logged in to post a comment.