0

If a user clicks on a file to download, I want the browser to display the contents if it can (PDFs, images) otherwise download it. For PDFs and images, if they choose to download the file, I want the proper file name to be in the dialog box. My code is:

header("Content-type: $mime");
header("Content-Disposition: attachment; filename=\"$name\"");
//send the file contents to the browser

This causes the file to be downloaded all the time. Are there additional header parameters I need to pass?

Floyd Resler
  • 1,786
  • 3
  • 22
  • 41

2 Answers2

1

Try this. What this is doing is that it passes in a file, and if the file is a PDF, then it will give the file to the browser, and then the browser will read the file.

<?php
  // Store the file name into variable
  $file = 'FileName.pdf';
  $filename = 'FileName.pdf';

  // Header content type
  header('Content-type: application/pdf');
    
  header('Content-Disposition: inline; filename="' . $filename . '"');
    
  header('Content-Transfer-Encoding: binary');
    
  header('Accept-Ranges: bytes');
    
  // Read the file
  @readfile($file);
?>

Below is an image of this working in action: Example

Reference:

GeeksForGeeks Link

undevable
  • 304
  • 1
  • 12
0
$extenionsAllowed = ['pdf','png','jpg']; // fill all here.

// converting the extension into small case
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));

// if one of the files that are to be shown
if(in_array($extension,$extenionsAllowed)){
    if($extension == 'pdf'){
      // pdfs are shown differently in browsers than image files
    }
    // code to show file
}
else{
   //code to download
}

you need to tweak header to show pdfs into the browser and for images, you can just open them directly. Read it here:

Display PDF on browser

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78