Emalawi19 commited on
Commit
04234c4
·
verified ·
1 Parent(s): 0a384f6

Update index.php

Browse files
Files changed (1) hide show
  1. index.php +93 -75
index.php CHANGED
@@ -1,100 +1,118 @@
1
  <?php
 
2
  header("Access-Control-Allow-Origin: *");
3
  header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
4
  header("Access-Control-Allow-Headers: Content-Type, Authorization");
5
- header("Content-Type: application/json; charset=UTF-8");
6
 
7
  if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
8
  http_response_code(200);
9
  exit();
10
  }
11
 
12
- // 1. Configure Hugging Face Repository Settings
13
  $hfToken = getenv('HF_TOKEN');
14
- $repoId = "Emalawi19/php-platform-storage"; // Replace with your actual username/dataset name
15
- $fileName = "data.json";
16
-
17
- // Hugging Face API Endpoints
18
- $hfUrl = "https://huggingface.co/api/datasets/{$repoId}/raw/main/{$fileName}";
19
- $uploadUrl = "https://huggingface.co/api/datasets/{$repoId}/upload/main/{$fileName}";
20
 
21
  $method = $_SERVER['REQUEST_METHOD'];
22
 
23
- switch ($method) {
24
- case 'GET':
25
- // 2. Fetch data from the permanent Dataset
26
- $ch = curl_init($hfUrl);
27
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
28
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
29
- "Authorization: Bearer {$hfToken}"
30
- ]);
31
-
32
- $response = curl_exec($ch);
33
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Fixed constant here
34
- curl_close($ch);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- // If the file doesn't exist yet, return an empty array
37
- if ($httpCode === 404) {
38
- echo json_encode([]);
39
- } else {
40
- echo $response;
41
- }
42
- break;
43
 
44
- case 'POST':
45
- // 3. Read existing data first so we don't overwrite it
46
- $ch = curl_init($hfUrl);
47
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
48
- curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer {$hfToken}"]);
49
- $existingDataRaw = curl_exec($ch);
50
- $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Fixed constant here
51
- curl_close($ch);
52
 
53
- $currentData = ($httpCode === 200) ? json_decode($existingDataRaw, true) : [];
 
 
 
 
54
 
55
- // Get incoming data from the frontend
56
- $inputJSON = file_get_contents('php://input');
57
- $input = json_decode($inputJSON, true);
 
 
 
58
 
59
- if (isset($input['message'])) {
60
- $newMessage = [
61
- "id" => uniqid(),
62
- "message" => htmlspecialchars($input['message']),
63
- "timestamp" => date('c')
64
- ];
65
- $currentData[] = $newMessage;
66
- $updatedContent = json_encode($currentData, JSON_PRETTY_PRINT);
 
 
67
 
68
- // 4. Push updated data back to the Hugging Face Dataset
69
- $ch = curl_init($uploadUrl);
70
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
71
- curl_setopt($ch, CURLOPT_POST, true);
72
- curl_setopt($ch, CURLOPT_POSTFIELDS, $updatedContent);
73
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
74
- "Authorization: Bearer {$hfToken}",
75
- "Content-Type: application/json"
76
- ]);
77
 
78
- $uploadResponse = curl_exec($ch);
79
- $uploadCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Fixed constant here
80
- curl_close($ch);
 
 
 
 
 
 
 
 
 
81
 
82
- if ($uploadCode === 200 || $uploadCode === 201) {
83
- http_response_code(201);
84
- echo json_encode(["status" => "success", "data" => $newMessage]);
85
- } else {
86
- http_response_code(500);
87
- echo json_encode(["status" => "error", "message" => "Failed to save to Hugging Face Dataset.", "details" => $uploadResponse]);
88
- }
89
- } else {
90
- http_response_code(400);
91
- echo json_encode(["status" => "error", "message" => "No message provided."]);
92
- }
93
- break;
94
 
95
- default:
96
- http_response_code(405);
97
- echo json_encode(["status" => "error", "message" => "Method not allowed"]);
98
- break;
 
 
 
 
 
99
  }
100
  ?>
 
1
  <?php
2
+ // 1. Setup Headers & CORS
3
  header("Access-Control-Allow-Origin: *");
4
  header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
5
  header("Access-Control-Allow-Headers: Content-Type, Authorization");
 
6
 
7
  if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
8
  http_response_code(200);
9
  exit();
10
  }
11
 
12
+ // 2. Configuration
13
  $hfToken = getenv('HF_TOKEN');
14
+ $repoId = "Emalawi19/php-platform-storage"; // Your permanent dataset
15
+ $spaceUrl = "https://emalawi19-advanced-php.hf.space"; // Base URL of your Space
 
 
 
 
16
 
17
  $method = $_SERVER['REQUEST_METHOD'];
18
 
19
+ // ---------------------------------------------------------
20
+ // GET REQUEST: Show a simple UI to test uploads visually
21
+ // ---------------------------------------------------------
22
+ if ($method === 'GET') {
23
+ echo '<!DOCTYPE html>
24
+ <html lang="en">
25
+ <head>
26
+ <meta charset="UTF-8">
27
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
28
+ <title>PHP Hosting Platform</title>
29
+ <style>
30
+ body { font-family: system-ui, sans-serif; background: #0f172a; color: white; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
31
+ .card { background: #1e293b; padding: 2rem; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.3); text-align: center; }
32
+ input[type="file"] { margin: 1rem 0; }
33
+ button { background: #3b82f6; color: white; border: none; padding: 10px 20px; border-radius: 6px; cursor: pointer; font-weight: bold; }
34
+ button:hover { background: #2563eb; }
35
+ </style>
36
+ </head>
37
+ <body>
38
+ <div class="card">
39
+ <h2>🚀 Deploy PHP Website</h2>
40
+ <p>Upload a .zip file containing your index.php</p>
41
+ <form method="POST" enctype="multipart/form-data">
42
+ <input type="file" name="site_zip" accept=".zip" required><br>
43
+ <button type="submit">Deploy Now</button>
44
+ </form>
45
+ </div>
46
+ </body>
47
+ </html>';
48
+ exit();
49
+ }
50
 
51
+ // ---------------------------------------------------------
52
+ // POST REQUEST: Process the ZIP and deploy the site
53
+ // ---------------------------------------------------------
54
+ if ($method === 'POST') {
55
+ header('Content-Type: application/json');
 
 
56
 
57
+ // Check if a file was actually uploaded
58
+ if (!isset($_FILES['site_zip']) || $_FILES['site_zip']['error'] !== UPLOAD_ERR_OK) {
59
+ http_response_code(400);
60
+ echo json_encode(["status" => "error", "message" => "Please upload a valid ZIP file."]);
61
+ exit;
62
+ }
 
 
63
 
64
+ $zipTempPath = $_FILES['site_zip']['tmp_name'];
65
+
66
+ // Generate a short, unique site ID (e.g., a1b2c3d4)
67
+ $siteId = substr(md5(uniqid(rand(), true)), 0, 8);
68
+ $extractPath = "/tmp/sites/" . $siteId;
69
 
70
+ // Create the unique directory for this user
71
+ if (!mkdir($extractPath, 0777, true)) {
72
+ http_response_code(500);
73
+ echo json_encode(["status" => "error", "message" => "Failed to create site directory."]);
74
+ exit;
75
+ }
76
 
77
+ // Unpack the ZIP file
78
+ $zip = new ZipArchive;
79
+ if ($zip->open($zipTempPath) === TRUE) {
80
+ $zip->extractTo($extractPath);
81
+ $zip->close();
82
+ } else {
83
+ http_response_code(500);
84
+ echo json_encode(["status" => "error", "message" => "Failed to extract ZIP file. Ensure it is a valid .zip format."]);
85
+ exit;
86
+ }
87
 
88
+ // Backup the ZIP to the Hugging Face Dataset for permanence
89
+ $zipContent = file_get_contents($zipTempPath);
90
+ $uploadUrl = "https://huggingface.co/api/datasets/{$repoId}/upload/main/sites/{$siteId}.zip";
 
 
 
 
 
 
91
 
92
+ $ch = curl_init($uploadUrl);
93
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
94
+ curl_setopt($ch, CURLOPT_POST, true);
95
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $zipContent);
96
+ curl_setopt($ch, CURLOPT_HTTPHEADER, [
97
+ "Authorization: Bearer {$hfToken}",
98
+ "Content-Type: application/zip"
99
+ ]);
100
+
101
+ $uploadResponse = curl_exec($ch);
102
+ $uploadCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
103
+ curl_close($ch);
104
 
105
+ // Generate the user's live URL!
106
+ $liveUrl = $spaceUrl . "/sites/" . $siteId . "/";
 
 
 
 
 
 
 
 
 
 
107
 
108
+ http_response_code(201);
109
+ echo json_encode([
110
+ "status" => "success",
111
+ "message" => "Site deployed successfully!",
112
+ "site_id" => $siteId,
113
+ "live_url" => $liveUrl,
114
+ "backup_status" => ($uploadCode === 200 || $uploadCode === 201) ? "Saved to Dataset" : "Backup Failed"
115
+ ]);
116
+ exit;
117
  }
118
  ?>