Files
PyCanvas/codestorage/default.php
Hugo H 09d60b29b3
All checks were successful
FTP Upload on Push / deploy (push) Successful in 8s
FTP Upload on Push / release (push) Successful in 8s
Added code storage api for storing code in the future
2025-12-26 18:08:52 +00:00

93 lines
2.7 KiB
PHP

<?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;
}
?>