Download files in any format
Supports file downloads in any format The function has two parameters. The first parameter is the file completion path on the server, and the second parameter is the download display file name.
- /**
- * Download an object
- * Filename does not include the suffix
- */
- Public function download ($ _ path, $ filename = ''){
- If (file_exists ($ _ path )){
- $ FullPath = CHtml: decode ($ _ path );
- $ Filename = $ filename? $ Filename: substr (strrchr ($ fullPath, '/'), 1 );
- // Parse Info/Get Extension
- $ Fsize = filesize ($ fullPath );
- $ Path_parts = pathinfo ($ fullPath );
- $ Ext = strtolower ($ path_parts ["extension"]);
- $ Filename. = '.'. $ ext;
- // Determine Content Type
- Switch ($ ext ){
- Case 'apk ':
- $ Ctype = 'application/vnd. android. package-archive ';
- Break;
- Case 'chm ':
- $ Ctype = 'application/octet-stream ';
- Break;
- Case "pdf ":
- $ Ctype = "application/pdf ";
- Break;
- Case "txt ":
- $ Ctype = "application/txt ";
- Break;
- Case "zip ":
- $ Ctype = "application/zip ";
- Break;
- Case "doc ":
- $ Ctype = "application/msword ";
- Break;
- Case "xls ":
- $ Ctype = "application/vnd. ms-excel ";
- Break;
- Case "ppt ":
- $ Ctype = "application/vnd. ms-powerpoint ";
- Break;
- Case "gif ":
- $ Ctype = "image/gif ";
- Break;
- Case "png ":
- $ Ctype = "image/png ";
- Break;
- Case "jpeg ":
- Case "jpg ":
- $ Ctype = "image/jpg ";
- Break;
- Default:
- $ Ctype = "application/force-download ";
- }
- $ Ua = $ _ SERVER ["HTTP_USER_AGENT"];
- $ Encoded_filename = rawurlencode ($ filename );
- $ Encoded_filename = str_replace ("+", "% 20", $ encoded_filename );
- Header ("Pragma: public"); // required
- Header ("Expires: 0 ");
- Header ("Cache-Control: must-revalidate, post-check = 0, pre-check = 0 ");
- Header ("Cache-Control: private", false); // required for certain browsers
- Header ("Content-Type: $ ctype ");
- // Header ('content-Disposition: attachment; filename = "'. rawurlencode ($ filename ).'"');
- If (preg_match ("/MSIE/", $ ua )){
- Header ('content-Disposition: attachment; filename = "'. $ encoded_filename .'"');
- } Else if (preg_match ("/Firefox/", $ ua )){
- Header ("Content-Disposition: attachment; filename * = utf8''". $ filename .'"');
- } Else {
- Header ('content-Disposition: attachment; filename = "'. $ filename .'"');
- }
- Header ("Content-Transfer-Encoding: binary ");
- Header ("Content-Length:". $ fsize );
- Ob_clean ();
- Flush ();
- Readfile ($ fullPath );
- } Else {
- Throw new Exception ('The file does not exist! ', 1 );
- }
- }
|