hungneox
hungneox

Reputation: 9839

PHP - What are the correct headers for downloading file?

I have a piece of code that allow users download file from server (document such as docs,docx,pdf etc).

Users can download files but it has some errors like the files were broken. For example, a MS Word file after download need to recovery to read content.

I wonder that if there is any mistake in this code (or problem when uploading?).

$size_of_file = filesize($download_path);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $file_name);
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $size_of_file);
//read file from physical path
readfile($download_path);

enter image description here

Upvotes: 1

Views: 1943

Answers (2)

hungneox
hungneox

Reputation: 9839

I found the root of the problem, I hav some extra spaces after php close tag. Thank you guys.

Upvotes: 1

Sudantha
Sudantha

Reputation: 16224

Did you try like this ?

<?php
    header("Content-type: application/vnd.ms-word");
    header("Content-Disposition: attachment; Filename=SaveAsWordDoc.doc");
?>

Upvotes: 1

Related Questions