1

I had some problems with a php download script. It's a pdf file and after hitting download, it throws the whole file as plain text instead of downloading it. Happens for jpeg and other files too.

This error only happens, once I wrapped a class around the code ->

<?php
class BaseClass {
    function __construct() {
       $this->makeDownload();
    }

    public function makeDownload()
    {
        $downloadfile = "./downloads/file.pdf";
        $filename = "file.pdf";
        $filesize = filesize($downloadfile);

        header("Content-Type: application/pdf"); 
        header("Content-Disposition: attachment; filename='$filename'"); 
        header("Content-Length: $filesize");

        readfile($downloadfile);
    }
}



// In BaseClass constructor
$obj = new BaseClass();
?>

The previouse webspace runs this code without any problems. The new webspace, as I wrote, throws something like this ->

%PDF-1.5 %âãÏÓ 144 0 obj <> endobj xref 144 41 0000000016 00000 n 00000.....

Without the wrapped class, everything works(downloads the pdf). So it's no the method what causes the error.

Is there any setting in the php.ini on the other webspace, which could cause a download wrapped in a class spams with the files sourcecode instead of downloading it?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149

1 Answers1

1

This means the HTTP headers aren't set correctly, namely Content-Type and Content-Disposition, which causes the browser to treat the response as pure text. This can be caused by two things:

  1. Your PHP isn't actually outputting those headers. The reason for this would be that headers cannot be output anymore because you've already sent content before. Enable error reporting to confirm this, you'll see an error message about this happening. Yes, this may work on one server but not another. See https://stackoverflow.com/a/8028987/476 for a great rundown of all possibilities.

  2. (Unlikely here, but for completeness:) PHP is outputting the headers just fine, but they're overridden by the web server. This is a web server configuration issue and the solution will greatly depend on the server in use and what you can and can't configure about it. Consult the documentation and/or contact your host.

Community
  • 1
  • 1
deceze
  • 510,633
  • 85
  • 743
  • 889
  • My script had an echo before invoking the download. This was causing the "headers already sent error" which was shown after I enabled the error report. I never thought this could bug a download, that's why I didn't added that echo to my example shown above. It's working now, thanks. – Robert Lange Dec 22 '15 at 13:16