-
Notifications
You must be signed in to change notification settings - Fork 10
/
Sendfile.php
270 lines (223 loc) · 6.93 KB
/
Sendfile.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
<?php
namespace Diversen;
use Exception;
/**
* Sends a file to a client, with support for (multiple) range requests.
* It is also able to throttle the download.",
*/
class Sendfile
{
/**
* if false we set content disposition from file that will be sent
*/
private string $disposition = '';
/**
* throttle speed in secounds
*/
private float $sec = 0.1;
/**
* bytes per $sec
*/
private int $bytes = 40960;
/**
* if contentType is false we try to guess it
*/
private string $contentType = '';
/**
* The number of seconds until the content expires.
* If not set, defaults to a date in the past.
*/
private ?int $expiresSeconds = null;
/**
* Sets the number of seconds until the content should be considered expired.
*/
public function setExpires(int $secs)
{
$this->expiresSeconds = $secs;
}
/**
* set content disposition. Name of file that will be sent to client
* if empty we try to guess it from file path
*/
public function setContentDisposition(string $file_name = '')
{
$this->disposition = $file_name;
}
/**
* set throttle speed
*/
public function throttle(float $sec = 0.1, int $bytes = 40960)
{
$this->sec = $sec;
$this->bytes = $bytes;
}
/**
* set content content type if empty we try to guess it
*/
public function setContentType(string $content_type = '')
{
$this->contentType = $content_type;
}
/**
* get name from path info
*/
private function getBaseName(string $file)
{
$info = pathinfo($file);
return $info['basename'];
}
/**
* Send the file
*/
public function send(string $file_path, bool $with_disposition = true)
{
if (!is_readable($file_path)) {
throw new Exception("File {$file_path} not found or inaccessible.");
}
$size = $this->prepareHeaders($file_path, $with_disposition);
if ($size === null) {
return null;
}
$range = $this->processRangeHeader($size);
$this->outputFileContents($file_path, $range);
}
/**
* Prepares and sends HTTP headers.
*/
private function prepareHeaders(string $file_path, bool $with_disposition): ?int
{
$size = filesize($file_path);
$lastModified = filemtime($file_path);
$etag = md5($file_path . $size . $lastModified);
header('Etag: "' . $etag . '"');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
if ($this->clientCacheIsValid($etag)) {
header("HTTP/1.1 304 Not Modified");
return null;
}
if ($with_disposition) {
$filename = $this->disposition ?: $this->getBaseName($file_path);
} else {
$filename = '';
}
$this->setDownloadHeaders($filename);
header('Content-Type: ' . ($this->contentType ?: $this->getContentType($file_path)));
header('Accept-Ranges: bytes');
header("Cache-control: must-revalidate, private");
header('Pragma: private');
$this->setExpiresHeader();
return $size;
}
/**
* Sets the Expires header based on the expiresSeconds property.
*/
private function setExpiresHeader()
{
if (is_null($this->expiresSeconds)) {
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
} else {
$expiresTime = gmdate('D, d M Y H:i:s', time() + $this->expiresSeconds) . ' GMT';
header("Expires: " . $expiresTime);
}
}
/**
* Checks if client cache is still valid.
*/
private function clientCacheIsValid(string $etag): bool
{
if (!isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
return false;
}
// Normalize ETag values for comparison
$clientEtag = trim($_SERVER['HTTP_IF_NONE_MATCH'], "\"");
$serverEtag = trim($etag);
// Optionally strip known suffixes like "-gzip" and "-gunzip"
// This is related to apache mod_deflate configuration
// I don't know if it's needed for other web servers
$clientEtag = preg_replace('/-gzip$/', '', $clientEtag);
$clientEtag = preg_replace('/-gunzip$/', '', $clientEtag);
return $clientEtag === $serverEtag;
}
/**
* Sets headers related to file download.
*/
private function setDownloadHeaders(string $filename)
{
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
if ($filename) {
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
}
}
/**
* Handles range requests.
*/
private function processRangeHeader(int $size): array
{
if (isset($_SERVER['HTTP_RANGE'])) {
list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
list($range) = explode(",", $range, 2);
list($range, $range_end) = explode("-", $range);
$range = intval($range);
$range_end = ($range_end !== '') ? intval($range_end) : $size - 1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: " . ($range_end - $range + 1));
header("Content-Range: bytes $range-$range_end/$size");
return [$range, $range_end];
} else {
header("Content-Length: $size");
return [0, $size - 1];
}
}
/**
* Outputs the file content.
*/
private function outputFileContents(string $file_path, array $range)
{
[$start, $end] = $range;
$this->cleanAll();
$file = @fopen($file_path, 'rb');
if (!$file) {
throw new Exception("Can not open file {$file_path} for reading.");
}
fseek($file, $start);
$bytes_send = $start;
while (!feof($file) && !connection_aborted() && $bytes_send <= $end) {
$buffer = fread($file, $this->bytes);
echo $buffer;
flush();
usleep($this->sec * 1000000);
$bytes_send += strlen($buffer);
}
fclose($file);
}
/**
* Get content type
*/
private function getContentType(string $path): string
{
$mimeType = 'application/octet-stream'; // Default MIME type if detection fails
if (!is_file($path)) {
return $mimeType;
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if ($finfo !== false) {
$detectedType = finfo_file($finfo, $path);
finfo_close($finfo);
if ($detectedType !== false) {
$mimeType = $detectedType;
}
}
return $mimeType;
}
/**
* clean all buffers
*/
private function cleanAll()
{
while (ob_get_level()) {
ob_end_clean();
}
}
}