Page 1 of 1

PHP: Simple Force-Download Function

PostPosted: Wed Oct 01, 2008 7:27 pm
by weblivehelp
Hi there again,

We are happy to continue providing tutorials that are accessed many times on a daily basis (too bad you people don't comment much...)!

Again, here's another helpful PHP Function for some people that allows you to force the user to download a file (instead of viewing it in the browser with a plugin, like an mp3 file or a pdf):

Code: Select all
<?php

$file = "/path/to/the/file.pdf";
$attachment_name = "here_goes_the_filename_for_download.pdf";

//-- NO Need to Edit Below
$file_extension = strtolower(substr(strrchr($file,"."),1));
$ext = substr(strrchr($file,"."),1);

switch( $file_extension ) {
   case "pdf": $ctype="application/pdf"; break;
   case "exe": $ctype="application/octet-stream"; break;
   case "zip": $ctype="application/zip"; break;
   case "odt": $ctype="application/vnd.oasis.opendocument.text";break;
   case "doc": $ctype="application/msword"; break;
   case "ods": $ctype="application/vnd.oasis.opendocument.spreadsheet";break;
   case "xls": $ctype="application/vnd.ms-excel"; break;
   case "odp": $ctype="application/vnd.oasis.opendocument.presentation";break;
   case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
   case "gif": $ctype="image/gif"; break;
   case "png": $ctype="image/png"; break;
   case "mp3": $ctype="audio/mpeg3";break;
   case "wav": $ctype="audio/wav";break;
   case "mpeg":
   case "mpg": $ctype="video/mpeg";break;
   case "avi": $ctype="video/avi";break;
   case "jpeg":
   case "jpg": $ctype="image/jpg"; break;
   default: $ctype="application/force-download";
}

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: ".$ctype."");
header("Content-Disposition: attachment; filename=\"".$attachment_name."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
readfile($file);
exit();

?>


Note that you can't do any output before this (otherwise you'll get "output started" errors), and you can put that code inside a function or something like that.

Hope we helped (again)!

Re: PHP: Simple Force-Download Function

PostPosted: Sun Dec 14, 2008 3:03 pm
by shadowman
Thanks! I was needing this, some customers on my site had problems about viewing pdf's on the site instead of downloading them!!

Keep up the good work!

Re: PHP: Simple Force-Download Function

PostPosted: Tue Jun 02, 2009 1:05 pm
by floridamary4
Nice work :)
thanks for sharing :)

web design chennai