Added code storage api for storing code in the future
This commit is contained in:
93
codestorage/default.php
Normal file
93
codestorage/default.php
Normal file
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
require_once 'secrets.php';
|
||||
|
||||
|
||||
$host = DB_HOST;
|
||||
$db_name = DB_NAME;
|
||||
$username = DB_USER;
|
||||
$password = DB_PASS;
|
||||
|
||||
try {
|
||||
$pdo = new PDO("mysql:host=$host;dbname=$db_name;charset=utf8mb4", $username, $password, [
|
||||
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
||||
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
||||
PDO::ATTR_EMULATE_PREPARES => false,
|
||||
]);
|
||||
|
||||
$createTableSql = "
|
||||
CREATE TABLE IF NOT EXISTS codeData (
|
||||
id BIGINT PRIMARY KEY,
|
||||
data LONGTEXT NOT NULL
|
||||
) ENGINE=InnoDB;
|
||||
";
|
||||
$pdo->exec($createTableSql);
|
||||
|
||||
// 3. Handle Request Methods
|
||||
$method = $_SERVER['REQUEST_METHOD'];
|
||||
|
||||
if ($method === 'GET') {
|
||||
// --- READ LOGIC ---
|
||||
if (isset($_GET['id'])) {
|
||||
$id = (int) $_GET['id'];
|
||||
|
||||
$stmt = $pdo->prepare("SELECT data FROM codeData WHERE id = ?");
|
||||
$stmt->execute([$id]);
|
||||
$row = $stmt->fetch();
|
||||
|
||||
if ($row) {
|
||||
header('Content-Type: text/plain');
|
||||
echo $row['data'];
|
||||
} else {
|
||||
http_response_code(404);
|
||||
echo "Error: Record with ID $id not found.";
|
||||
}
|
||||
} else {
|
||||
http_response_code(400);
|
||||
echo "Error: Missing 'id' parameter in query string.";
|
||||
}
|
||||
|
||||
} elseif ($method === 'POST') {
|
||||
// --- WRITE LOGIC ---
|
||||
// Get raw POST body
|
||||
$inputData = file_get_contents('php://input');
|
||||
|
||||
if (!empty($inputData)) {
|
||||
$idGenerated = false;
|
||||
$newId = 0;
|
||||
|
||||
// Generate a unique random ID and ensure it doesn't collide
|
||||
while (!$idGenerated) {
|
||||
$newId = mt_rand(100000, 999999999); // Range for the random ID
|
||||
|
||||
// Check if ID exists
|
||||
$checkStmt = $pdo->prepare("SELECT id FROM codeData WHERE id = ?");
|
||||
$checkStmt->execute([$newId]);
|
||||
if (!$checkStmt->fetch()) {
|
||||
$idGenerated = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Insert the new row
|
||||
$insertStmt = $pdo->prepare("INSERT INTO codeData (id, data) VALUES (?, ?)");
|
||||
$insertStmt->execute([$newId, $inputData]);
|
||||
|
||||
header('Content-Type: application/json');
|
||||
echo json_encode(['id' => $newId, 'status' => 'success']);
|
||||
} else {
|
||||
http_response_code(400);
|
||||
echo "Error: POST body is empty.";
|
||||
}
|
||||
|
||||
} else {
|
||||
// Unsupported Method
|
||||
http_response_code(405);
|
||||
echo "Error: Method $method not allowed.";
|
||||
}
|
||||
|
||||
} catch (PDOException $e) {
|
||||
// Handle connection or query errors
|
||||
http_response_code(500);
|
||||
echo "Database Error: " . $e->getMessage();
|
||||
exit;
|
||||
}
|
||||
?>
|
||||
Reference in New Issue
Block a user