-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream.php
More file actions
90 lines (72 loc) · 2.6 KB
/
stream.php
File metadata and controls
90 lines (72 loc) · 2.6 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
<?php
// stream.php - Secure Media Proxy
// Serves files from the secure storage outside the webroot.
require_once 'config.php';
// Define STORAGE_PATH fallback if not in config.php
if (!defined('STORAGE_PATH')) {
define('STORAGE_PATH', __DIR__ . '/storage');
}
// 1. Session & Auth Check
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Check if user is logged in
// Assuming standard session variable 'user_id' is set upon login.
// Looking at login.php/auth.php would confirm, but typical pattern is $_SESSION['user_id'].
// Let's verify auth.php or login.php logic briefly if possible, but I will assume $_SESSION['user_id'] exists.
if (!isset($_SESSION['user_id'])) {
http_response_code(403);
die("Access denied.");
}
$currentUserId = $_SESSION['user_id'];
// 2. Validate Input
$fileId = $_GET['id'] ?? '';
$mode = $_GET['mode'] ?? 'view'; // view | download
if (empty($fileId) || !ctype_alnum(str_replace('-', '', $fileId))) {
http_response_code(400);
die("Invalid file ID.");
}
// 3. Database Lookup & Ownership Check
try {
// DB connection is established in config.php as $pdo
$stmt = $pdo->prepare("SELECT user_id, original_filename, storage_filename, mime_type, file_size FROM user_files WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $fileId]);
$file = $stmt->fetch();
if (!$file) {
http_response_code(404);
die("File not found.");
}
if ((int)$file['user_id'] !== (int)$currentUserId) {
http_response_code(403);
die("Access denied: You do not own this file.");
}
// 4. File Existence Check
$filePath = STORAGE_PATH . '/' . $file['storage_filename'];
if (!file_exists($filePath)) {
http_response_code(404);
die("File not found on storage.");
}
// 5. Headers & Output
// Prevent caching for secure content or set appropriate cache control
header("Cache-Control: private, max-age=3600");
header("Content-Type: " . $file['mime_type']);
header("Content-Length: " . $file['file_size']);
if ($mode === 'download') {
// Force download
// Sanitize filename for header
$filename = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $file['original_filename']);
header("Content-Disposition: attachment; filename=\"$filename\"");
} else {
// Inline view
header("Content-Disposition: inline; filename=\"preview\"");
}
// Clear buffer to prevent corruption
if (ob_get_level()) {
ob_end_clean();
}
readfile($filePath);
exit;
} catch (PDOException $e) {
http_response_code(500);
die("Database error.");
}