Guesser
Guesser

Reputation: 1857

PHP - Force download or view in browser depending on file type

I am using the following headers to force a download but I need to try and have the browser display certain files like PDF's and JPG's if that is the file type, finding the exntension is easy enough but how can I alter these headers to open the file in the browser?

header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
$header="Content-Disposition: attachment; filename=".$filename.";";
header($header);
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: $filesize");

Upvotes: 2

Views: 1847

Answers (1)

cmbuckley
cmbuckley

Reputation: 42458

In order to display a file in the browser, you'll need to use the correct MIME type. You can set it yourself based on file extension, or you can use the finfo module:

function getContentType($filename) {
    $finfo = new finfo(FILEINFO_MIME);
    return $finfo->file($filename);
}

header("Content-Type: " . getContentType($filename));

Without this, the browser will probably assume that it can't handle the application/octet-stream content, and force a download anyway.

You should also only send the Content-Disposition header if you want to force the file to be downloaded. If you remove that header, then the browser can decide if it should display the file or download it.

Upvotes: 4

Related Questions