-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsave_invoice.php
More file actions
83 lines (67 loc) · 2.3 KB
/
save_invoice.php
File metadata and controls
83 lines (67 loc) · 2.3 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
<?php
declare(strict_types=1);
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/auth.php';
require_login();
header('Content-Type: application/json');
if (!isset($_FILES['file']) || !is_array($_FILES['file'])) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Missing file upload.']);
exit;
}
$file = $_FILES['file'];
if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Upload failed.']);
exit;
}
$maxBytes = 10 * 1024 * 1024;
if (($file['size'] ?? 0) <= 0 || ($file['size'] ?? 0) > $maxBytes) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Invalid file size.']);
exit;
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file['tmp_name']) ?: 'application/octet-stream';
$allowed = [
'application/pdf' => 'pdf',
'image/png' => 'png',
'image/jpeg' => 'jpg',
'image/webp' => 'webp'
];
if (!isset($allowed[$mime])) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Unsupported file type.']);
exit;
}
$raw = file_get_contents($file['tmp_name']);
if ($raw === false) {
http_response_code(500);
echo json_encode(['ok' => false, 'error' => 'Could not read uploaded file.']);
exit;
}
$fileHashHex = hash('sha256', $raw);
$ext = $allowed[$mime];
$uploadDir = __DIR__ . '/storage/invoices';
if (!is_dir($uploadDir) && !mkdir($uploadDir, 0775, true) && !is_dir($uploadDir)) {
http_response_code(500);
echo json_encode(['ok' => false, 'error' => 'Could not create upload directory.']);
exit;
}
$storedName = $fileHashHex . '.' . $ext;
$storedPath = $uploadDir . '/' . $storedName;
if (!move_uploaded_file($file['tmp_name'], $storedPath)) {
http_response_code(500);
echo json_encode(['ok' => false, 'error' => 'Could not store uploaded file.']);
exit;
}
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$documentUrl = $scheme . '://' . $host . '/storage/invoices/' . rawurlencode($storedName);
echo json_encode([
'ok' => true,
'file_hash_hex' => $fileHashHex,
'document_path' => 'storage/invoices/' . $storedName,
'document_url' => $documentUrl,
'document_mime' => $mime
]);