-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.php
More file actions
50 lines (37 loc) · 1.19 KB
/
Copy pathapi.php
File metadata and controls
50 lines (37 loc) · 1.19 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
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
$file = __DIR__ . '/compras.json';
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
exit(0);
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if (file_exists($file)) {
$data = file_get_contents($file);
echo $data ? $data : json_encode([]);
} else {
echo json_encode([]);
}
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = file_get_contents('php://input');
$decoded = json_decode($input, true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON data']);
exit;
}
if (file_put_contents($file, json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE))) {
echo json_encode(['success' => true, 'data' => $decoded]);
} else {
http_response_code(500);
echo json_encode(['error' => 'Could not save data to file']);
}
exit;
}
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
?>