-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
428 lines (398 loc) · 14.1 KB
/
index.php
File metadata and controls
428 lines (398 loc) · 14.1 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
<?php
declare(strict_types=1);
// Ensure correct encoding for multibyte file names
mb_internal_encoding('UTF-8');
// Root of the website (current directory where this file lives)
$ROOT_DIR = __DIR__;
// Polyfill for PHP < 8.0
if (!function_exists('str_starts_with')) {
function str_starts_with(string $haystack, string $needle): bool {
return strpos($haystack, $needle) === 0;
}
}
// Sessions for password-protected paths
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
// Helpers
function h(string $value): string {
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function isSafeRelativePath(string $relativePath): bool {
if ($relativePath === '') {
return true;
}
$segments = explode('/', $relativePath);
foreach ($segments as $segment) {
if ($segment === '' || $segment === '.' || $segment === '..') {
return false;
}
if (str_starts_with($segment, '.')) { // hide dot files/folders
return false;
}
}
return true;
}
function humanFileSize(int $bytes): string {
if ($bytes < 1024) {
return $bytes . ' B';
}
$units = ['KB','MB','GB','TB','PB'];
$index = 0;
$size = $bytes / 1024;
while ($size >= 1024 && $index < count($units) - 1) {
$size /= 1024;
$index++;
}
return sprintf('%.2f %s', $size, $units[$index]);
}
function formatDate(int $timestamp): string {
return date('Y-m-d H:i', $timestamp);
}
// Pretty URL helpers
function getBaseUriPrefix(): string {
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
$scriptDir = str_replace('\\', '/', dirname($scriptName));
if ($scriptDir === '/' || $scriptDir === '\\') {
return '';
}
return rtrim($scriptDir, '/');
}
function decodePath(string $path): string {
$path = str_replace('\\', '/', $path);
$path = preg_replace('#/+#', '/', $path);
$path = trim($path, '/');
if ($path === '') { return ''; }
$parts = explode('/', $path);
$decoded = [];
foreach ($parts as $p) { $decoded[] = rawurldecode($p); }
return implode('/', $decoded);
}
function pathToHref(string $rel): string {
$base = getBaseUriPrefix();
if ($rel === '') { return ($base === '' ? '/' : $base . '/'); }
$parts = explode('/', $rel);
$enc = [];
foreach ($parts as $p) { $enc[] = rawurlencode($p); }
return ($base === '' ? '' : $base) . '/' . implode('/', $enc);
}
function downloadHref(string $rel): string {
$base = getBaseUriPrefix();
return ($base === '' ? '' : $base . '/') . 'download.php?p=' . rawurlencode($rel);
}
// Determine current directory from request URI
$basePrefix = getBaseUriPrefix();
$reqPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
if ($basePrefix !== '' && str_starts_with($reqPath, $basePrefix . '/')) {
$reqPath = substr($reqPath, strlen($basePrefix));
}
if ($reqPath === '' || $reqPath === '/') {
$requestedRelDir = '';
} else {
if (str_starts_with($reqPath, '/')) { $reqPath = substr($reqPath, 1); }
if (str_starts_with($reqPath, 'index.php')) {
$rest = substr($reqPath, strlen('index.php'));
$reqPath = ltrim($rest, '/');
}
$requestedRelDir = decodePath($reqPath);
}
if (!isSafeRelativePath($requestedRelDir)) {
http_response_code(400);
header('Content-Type: text/plain; charset=utf-8');
echo "非法路径";
exit;
}
// Hidden/password rules helpers
function normalizeRel(string $rel): string {
$rel = str_replace('\\', '/', $rel);
$rel = trim($rel);
$rel = trim($rel, '/');
return $rel;
}
function readEnvLines(string $file): array {
if (!is_file($file)) { return []; }
$lines = @file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines === false) { return []; }
$out = [];
foreach ($lines as $line) {
$line = trim($line);
if ($line === '' || $line[0] === '#' || $line[0] === ';') { continue; }
$out[] = $line;
}
return $out;
}
function loadHiddenPaths(string $rootDir): array {
$raw = readEnvLines($rootDir . DIRECTORY_SEPARATOR . 'hide.env');
$hidden = [];
foreach ($raw as $entry) {
$entry = normalizeRel($entry);
if ($entry !== '' && !in_array($entry, $hidden, true)) { $hidden[] = $entry; }
}
usort($hidden, function($a, $b) { return strlen($b) <=> strlen($a); });
return $hidden;
}
function isHiddenPath(string $rel, array $hidden): bool {
if ($rel === '') { return false; }
foreach ($hidden as $h) {
if ($rel === $h || str_starts_with($rel, $h . '/')) { return true; }
}
return false;
}
function loadPasswordRules(string $rootDir): array {
$raw = readEnvLines($rootDir . DIRECTORY_SEPARATOR . 'password.env');
$rules = [];
foreach ($raw as $line) {
$path = '';
$pass = '';
if (strpos($line, '=') !== false) {
[$left, $right] = explode('=', $line, 2);
$path = normalizeRel($left);
$pass = trim($right);
} else {
$parts = preg_split('/\s+/', $line, 2);
if ($parts !== false && count($parts) === 2) {
$path = normalizeRel($parts[0]);
$pass = trim($parts[1]);
}
}
if ($path !== '' && $pass !== '') { $rules[] = ['path' => $path, 'password' => $pass]; }
}
usort($rules, function($a, $b) { return strlen($b['path']) <=> strlen($a['path']); });
return $rules;
}
function findPasswordRuleFor(string $rel, array $rules): ?array {
if ($rel === '') { return null; }
foreach ($rules as $rule) {
$prefix = $rule['path'];
if ($rel === $prefix || str_starts_with($rel, $prefix . '/')) { return $rule; }
}
return null;
}
function hasPasswordAccess(string $rel, array $rules): bool {
$rule = findPasswordRuleFor($rel, $rules);
if ($rule === null) { return true; }
$allowed = isset($_SESSION['pw_ok']) && is_array($_SESSION['pw_ok']) ? $_SESSION['pw_ok'] : [];
foreach ($allowed as $prefix) {
if ($rule['path'] === $prefix && ($rel === $prefix || str_starts_with($rel, $prefix . '/'))) { return true; }
}
return false;
}
function grantPasswordAccess(string $prefix): void {
if (!isset($_SESSION['pw_ok']) || !is_array($_SESSION['pw_ok'])) { $_SESSION['pw_ok'] = []; }
if (!in_array($prefix, $_SESSION['pw_ok'], true)) { $_SESSION['pw_ok'][] = $prefix; }
}
$hiddenPaths = loadHiddenPaths($ROOT_DIR);
$passwordRules = loadPasswordRules($ROOT_DIR);
// If current path is hidden entirely, show 404
if (isHiddenPath($requestedRelDir, $hiddenPaths)) {
http_response_code(404);
header('Content-Type: text/plain; charset=utf-8');
echo '未找到资源';
exit;
}
// Handle password submission
$authError = '';
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' && isset($_POST['password'])) {
$rule = findPasswordRuleFor($requestedRelDir, $passwordRules);
if ($rule !== null) {
$input = (string)($_POST['password'] ?? '');
if (hash_equals($rule['password'], $input)) {
grantPasswordAccess($rule['path']);
header('Location: ' . pathToHref($requestedRelDir));
exit;
} else {
$authError = '密码错误,请重试。';
}
}
}
$absoluteDir = realpath($ROOT_DIR . DIRECTORY_SEPARATOR . ($requestedRelDir === '' ? '.' : $requestedRelDir));
if ($absoluteDir === false || strpos($absoluteDir, $ROOT_DIR) !== 0 || !is_dir($absoluteDir)) {
// Fallback to root if anything invalid
$absoluteDir = $ROOT_DIR;
$requestedRelDir = '';
}
// Scan directory contents
$entries = @scandir($absoluteDir);
if ($entries === false) {
$entries = [];
}
$directories = [];
$files = [];
foreach ($entries as $entry) {
if ($entry === '.' || $entry === '..') {
continue;
}
if (str_starts_with($entry, '.')) { // hide dot files/folders
continue;
}
$fullPath = $absoluteDir . DIRECTORY_SEPARATOR . $entry;
if (is_dir($fullPath)) {
$childCount = 0;
$childEntries = @scandir($fullPath);
if ($childEntries !== false) {
foreach ($childEntries as $c) {
if ($c === '.' || $c === '..' || str_starts_with($c, '.')) {
continue;
}
$childCount++;
}
}
$relPath = $requestedRelDir === '' ? $entry : ($requestedRelDir . '/' . $entry);
if (isHiddenPath($relPath, $hiddenPaths)) { continue; }
$directories[] = [
'name' => $entry,
'rel' => $relPath,
'mtime' => @filemtime($fullPath) ?: 0,
'count' => $childCount,
];
} elseif (is_file($fullPath)) {
$relPath = $requestedRelDir === '' ? $entry : ($requestedRelDir . '/' . $entry);
if (isHiddenPath($relPath, $hiddenPaths)) { continue; }
$files[] = [
'name' => $entry,
'rel' => $relPath,
'mtime' => @filemtime($fullPath) ?: 0,
'size' => @filesize($fullPath) ?: 0,
'ext' => strtolower(pathinfo($entry, PATHINFO_EXTENSION)),
];
}
}
// Sort by name (case-insensitive)
usort($directories, function(array $a, array $b) {
return strcmp(mb_strtolower($a['name']), mb_strtolower($b['name']));
});
usort($files, function(array $a, array $b) {
return strcmp(mb_strtolower($a['name']), mb_strtolower($b['name']));
});
header('Content-Type: text/html; charset=utf-8');
?>
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>文件浏览器</title>
<link rel="stylesheet" href="<?php echo h(pathToHref('assets/style.css')); ?>" />
</head>
<body>
<header class="site-header">
<div class="container">
<h1 class="title">文件浏览器</h1>
<p class="subtitle">浏览并下载当前网站目录下的文件</p>
</div>
</header>
<main class="container page">
<nav class="breadcrumbs">
<span>当前位置:</span>
<?php
$crumbs = [];
if ($requestedRelDir === '') {
$crumbs[] = '<span class="crumb">根目录</span>';
} else {
$crumbs[] = '<a class="crumb" href="' . h(pathToHref('')) . '">根目录</a>';
$parts = explode('/', $requestedRelDir);
$pathAcc = [];
foreach ($parts as $idx => $part) {
$pathAcc[] = $part;
$rel = implode('/', $pathAcc);
$crumbs[] = '<a class="crumb" href="' . h(pathToHref($rel)) . '">' . h($part) . '</a>';
}
}
echo implode('<span class="sep">/</span>', $crumbs);
?>
</nav>
<?php if ($requestedRelDir !== ''): ?>
<?php
$parent = dirname($requestedRelDir);
if ($parent === '.' || $parent === DIRECTORY_SEPARATOR) {
$parent = '';
}
?>
<div class="toolbar">
<a class="btn" href="<?php echo h(pathToHref($parent)); ?>">返回上一级</a>
<a class="btn outline" href="<?php echo h(pathToHref('')); ?>">回到根目录</a>
</div>
<?php endif; ?>
<?php if (!hasPasswordAccess($requestedRelDir, $passwordRules)): ?>
<section class="listing">
<div class="card auth-card">
<form method="post" action="<?php echo h(pathToHref($requestedRelDir)); ?>">
<h2>该目录受密码保护</h2>
<div class="form-group">
<label for="password">请输入访问密码:</label>
<input type="password" id="password" name="password" required />
</div>
<?php if (!empty($authError)): ?>
<div class="error"><?php echo h($authError); ?></div>
<?php endif; ?>
<div class="form-actions">
<button class="btn primary" type="submit">确认</button>
<a class="btn outline" href="<?php echo h(pathToHref('')); ?>">返回首页</a>
</div>
</form>
</div>
</section>
<?php else: ?>
<section class="listing">
<div class="card">
<table class="file-table">
<thead>
<tr>
<th>名称</th>
<th class="type-col">类型</th>
<th class="size-col">大小</th>
<th class="date-col">修改时间</th>
<th class="actions-col">操作</th>
</tr>
</thead>
<tbody>
<?php if (empty($directories) && empty($files)): ?>
<tr>
<td colspan="5" class="empty">空文件夹</td>
</tr>
<?php endif; ?>
<?php foreach ($directories as $dir): ?>
<tr>
<td>
<a class="file-link icon-folder" href="<?php echo h(pathToHref($dir['rel'])); ?>" title="打开文件夹">
<?php echo h($dir['name']); ?>
</a>
<span class="muted count">(<?php echo (int)$dir['count']; ?> 项)</span>
</td>
<td class="muted">文件夹</td>
<td class="muted">-</td>
<td class="muted"><?php echo h(formatDate((int)$dir['mtime'])); ?></td>
<td>
<a class="btn small" href="<?php echo h(pathToHref($dir['rel'])); ?>">打开</a>
</td>
</tr>
<?php endforeach; ?>
<?php foreach ($files as $file): ?>
<?php $extClass = $file['ext'] !== '' ? (' ext-' . preg_replace('/[^a-z0-9_-]/i', '-', $file['ext'])) : ''; ?>
<tr>
<td>
<a class="file-link icon-file<?php echo h($extClass); ?>" href="<?php echo h(downloadHref($file['rel'])); ?>" title="下载文件">
<?php echo h($file['name']); ?>
</a>
</td>
<td class="muted">文件</td>
<td class="muted"><?php echo h(humanFileSize((int)$file['size'])); ?></td>
<td class="muted"><?php echo h(formatDate((int)$file['mtime'])); ?></td>
<td>
<a class="btn small primary" href="<?php echo h(downloadHref($file['rel'])); ?>">下载</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</section>
<?php endif; ?>
</main>
<footer class="site-footer">
<div class="container">
<span class="muted">© <?php echo date('Y'); ?> 文件浏览器</span>
</div>
</footer>
</body>
</html>