Siva
Siva

Reputation: 1133

PDF file download using PHP is getting corrupted in server

I've implemented a download script using PHP headers to download PDF files. My script is working fine and downloading the corresponding PDF file also in my localhost but that script is not working in my server.

My code is:

header("Content-Disposition: attachment; filename='dfile.pdf'");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-type: application/pdf;");

readfile("http://www.education.gov.yk.ca/pdf/pdf-test.pdf");

In my server file browser is appearing fine and downloading the file also as dfile.pdf, but If I try to open the downloaded file then I'm getting an error message of the file has been damaged. Any of my server settings causing this issue or something else?

Any suggestion to fix this problem is much appreciable.

Note: I think this might be an issue with my server PHP settings, can anybody tell me whether the "readfile" function need any PHP setting to enable in my server?

Thanks in advance, Siva...

Upvotes: 1

Views: 9197

Answers (3)

cristi
cristi

Reputation: 1

Try using this code:

$file = 'monkey.pdf';

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}

Upvotes: 0

Siva
Siva

Reputation: 1133

This issue is because of my server PHP settings, 'allow_url_fopen' setting is not enabled in my server. I'm handling this situation by using the CURL, anyway thanks for all of your support.

Upvotes: 0

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 30013

I think PHP outputs some warning before PDF file body. Check that.

Upvotes: 3

Related Questions