73 lines
2.3 KiB
PHP
73 lines
2.3 KiB
PHP
<?php
|
|
header('Content-Type: application/json');
|
|
require_once __DIR__ . '/db/config.php';
|
|
|
|
/**
|
|
* Generates a random, URL-friendly string of a given length.
|
|
*/
|
|
function generate_random_id($length = 8) {
|
|
return substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', $length)), 0, $length);
|
|
}
|
|
|
|
$method = $_SERVER['REQUEST_METHOD'];
|
|
|
|
try {
|
|
$pdo = db();
|
|
|
|
if ($method === 'POST') {
|
|
$input = json_decode(file_get_contents('php://input'), true);
|
|
$code = $input['code'] ?? null;
|
|
|
|
if (!$code) {
|
|
http_response_code(400); // Bad Request
|
|
echo json_encode(['error' => 'Code content is missing.']);
|
|
exit;
|
|
}
|
|
|
|
// Loop to ensure the generated ID is unique
|
|
do {
|
|
$id = generate_random_id();
|
|
$stmt = $pdo->prepare("SELECT id FROM snippets WHERE id = ?");
|
|
$stmt->execute([$id]);
|
|
} while ($stmt->fetchColumn());
|
|
|
|
$stmt = $pdo->prepare("INSERT INTO snippets (id, code) VALUES (?, ?)");
|
|
$stmt->execute([$id, $code]);
|
|
|
|
http_response_code(201); // Created
|
|
echo json_encode(['id' => $id]);
|
|
|
|
} elseif ($method === 'GET') {
|
|
$id = $_GET['id'] ?? null;
|
|
|
|
if (!$id) {
|
|
http_response_code(400); // Bad Request
|
|
echo json_encode(['error' => 'Snippet ID is missing.']);
|
|
exit;
|
|
}
|
|
|
|
$stmt = $pdo->prepare("SELECT code, created_at FROM snippets WHERE id = ?");
|
|
$stmt->execute([$id]);
|
|
$snippet = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
if ($snippet) {
|
|
echo json_encode($snippet);
|
|
} else {
|
|
http_response_code(404); // Not Found
|
|
echo json_encode(['error' => 'Snippet not found.']);
|
|
}
|
|
} else {
|
|
http_response_code(405); // Method Not Allowed
|
|
echo json_encode(['error' => 'Method not allowed.']);
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
http_response_code(500); // Internal Server Error
|
|
error_log("Database error: " . $e->getMessage());
|
|
echo json_encode(['error' => 'An internal server error occurred.']);
|
|
} catch (Exception $e) {
|
|
http_response_code(500); // Internal Server Error
|
|
error_log("General error: " . $e->getMessage());
|
|
echo json_encode(['error' => 'An internal server error occurred.']);
|
|
}
|