@@ -98,21 +98,46 @@ public static function runControllerFunction($dir_name,$class,$func)
98
98
return $ status ;
99
99
}
100
100
101
-
102
- public static function download ($ path ,$ download_name =null )
101
+
102
+ /**
103
+ * Downloads a file from the server to the client with appropriate headers and content type.
104
+ *
105
+ * @param string $file_path The path of the file to download.
106
+ * @param string|null $download_name The filename that will be shown in the download prompt. Defaults to the basename of the file_path if null.
107
+ * @return void
108
+ */
109
+ public static function download ($ file_path , $ download_name = null )
103
110
{
104
- if ($ download_name ==null ) {
105
- $ download_name =basename ($ path );
106
- }
107
-
108
- header ("Expires: 0 " );
109
- header ("Last-Modified: " . gmdate ("D, d M Y H:i:s " ) . " GMT " );
110
- header ("Cache-Control: no-store, no-cache, must-revalidate " );
111
- header ("Cache-Control: post-check=0, pre-check=0 " , false );
112
- header ("Pragma: no-cache " ); header ("Content-type: application/file " );
113
- header ('Content-length: ' .filesize ($ path ));
114
- header ('Content-disposition: attachment; filename= ' .$ download_name );
115
- readfile ($ path );
111
+ // Load FileInfo module to determine the MIME type of the file
112
+ $ file_info = finfo_open (FILEINFO_MIME_TYPE );
113
+
114
+ if (is_file ($ file_path )) {
115
+ $ file_size = filesize ($ file_path );
116
+ $ download_name = $ download_name ?? basename ($ file_path );
117
+
118
+ // Determine the content type based on the MIME type of the file
119
+ $ content_type = finfo_file ($ file_info , $ file_path );
120
+
121
+ // Set headers for streaming
122
+ header ('Content-Type: ' . $ content_type );
123
+ header ('Content-Transfer-Encoding: Binary ' );
124
+ header ('Content-Length: ' . $ file_size );
125
+ header ('Content-disposition: attachment; filename=" ' . $ download_name . '" ' );
126
+
127
+ // Open the file and stream it to the output buffer in small chunks
128
+ $ file = fopen ($ file_path , 'rb ' );
129
+ while (!feof ($ file )) {
130
+ print (fread ($ file , 1024 * 8 ));
131
+ ob_flush ();
132
+ flush ();
133
+ }
134
+ fclose ($ file );
135
+ exit ;
136
+ } else {
137
+ echo "Error: File not found. " ;
138
+ }
139
+
140
+ finfo_close ($ file_info ); // Close the FileInfo module
116
141
}
117
142
118
143
public static function showImage ($ path )
0 commit comments