1

I am able to display file with url: For example

echo '<a href="'.$file_url.'" target="_blank">'.$path_parts['basename'].'</a>';

How can I make this file downloadable? In case of pdf files, it is not downloading and opening in new tab as i have added target.

1
  • opening in new tab is due to browser plugin. try to disable
    – monymirza
    Commented Mar 19, 2013 at 8:06

2 Answers 2

4

If you want to Force download PDF files. if your server is Apache

put this line in your .htaccess file.

AddType application/octet-stream .pdf

If there is any issues with browser try this

SetEnvIf Request_URI "\.pdf$" requested_pdf=pdf
Header add Content-Disposition "attachment" env=requested_pdf

If its NGINX

location ~* /orig/(.+\.jpg)$ {
    internal;
    add_header Content-disposition "attachment; filename=$1";
}
1
  • If its NGINX...what i t means....I have tried Addtype in htaccess..Some pdf are working fine some are not..
    – Srinu
    Commented Mar 19, 2013 at 6:54
0

In addition to doing it from apache's side via the httpd.conf or .htaccess with above answer ... You can do this with a module as well:

<?php
function mymodule_mimetype_override_file_mimetype_mapping_alter(&$mapping) {  
  $new_mime_type = 'application/octet-stream'; //already in mimetypes so below array addition wont happen, but put here in case you want to add your own type

  if ( !in_array($new_mime_type, $mapping['mimetypes'])) {
    $mapping['mimetypes'][] = $new_mime_type; //mapping['mimetypes']['octetstream']
  }
  $index = array_search($new_mime_type, $mapping['mimetypes']);
  $mapping['extensions']['pdf'] = 15; //manually setting for now, could have used $index; //15 is octet-stream, 18 is pdf
}

//also added this for my HTTPS site since IE8 couldnt download/display any files if it doesn't have certain cache headers for ssl websites ... heh, booooooo
function mymodule_override_file_download($filepath) {
  header("Cache-Control: private, must-revalidate"); //may have to set Pragma too but not in my case
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.