Merge branch 'maint/7.0'
[ninja.git] / system / helpers / download.php
blobe6268533d23a364088a3b59a51bef4a64e36a980
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3 * Download helper class.
5 * $Id: download.php 3917 2009-01-21 03:06:22Z zombor $
7 * @package Core
8 * @author Kohana Team
9 * @copyright (c) 2007-2008 Kohana Team
10 * @license http://kohanaphp.com/license.html
12 class download {
14 /**
15 * Force a download of a file to the user's browser. This function is
16 * binary-safe and will work with any MIME type that Kohana is aware of.
18 * @param string a file path or file name
19 * @param mixed data to be sent if the filename does not exist
20 * @param string suggested filename to display in the download
21 * @return void
23 public static function force($filename = NULL, $data = NULL, $nicename = NULL)
25 if (empty($filename))
26 return FALSE;
28 if (is_file($filename))
30 // Get the real path
31 $filepath = str_replace('\\', '/', realpath($filename));
33 // Set filesize
34 $filesize = filesize($filepath);
36 // Get filename
37 $filename = substr(strrchr('/'.$filepath, '/'), 1);
39 // Get extension
40 $extension = strtolower(substr(strrchr($filepath, '.'), 1));
42 else
44 // Get filesize
45 $filesize = strlen($data);
47 // Make sure the filename does not have directory info
48 $filename = substr(strrchr('/'.$filename, '/'), 1);
50 // Get extension
51 $extension = strtolower(substr(strrchr($filename, '.'), 1));
54 // Get the mime type of the file
55 $mime = Kohana::config('mimes.'.$extension);
57 if (empty($mime))
59 // Set a default mime if none was found
60 $mime = array('application/octet-stream');
63 // Generate the server headers
64 header('Content-Type: '.$mime[0]);
65 header('Content-Disposition: attachment; filename="'.(empty($nicename) ? $filename : $nicename).'"');
66 header('Content-Transfer-Encoding: binary');
67 header('Content-Length: '.sprintf('%d', $filesize));
69 // More caching prevention
70 header('Expires: 0');
72 if (Kohana::user_agent('browser') === 'Internet Explorer')
74 // Send IE headers
75 header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
76 header('Pragma: public');
78 else
80 // Send normal headers
81 header('Pragma: no-cache');
84 // Clear the output buffer
85 Kohana::close_buffers(FALSE);
87 if (isset($filepath))
89 // Open the file
90 $handle = fopen($filepath, 'rb');
92 // Send the file data
93 fpassthru($handle);
95 // Close the file
96 fclose($handle);
98 else
100 // Send the file data
101 echo $data;
105 } // End download