PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$db->exec("
CREATE TABLE IF NOT EXISTS pastes (
id TEXT PRIMARY KEY,
content TEXT NOT NULL,
created_at INTEGER NOT NULL,
expires_at INTEGER NULL
)
");
function h(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function generatePasteId(PDO $db): string
{
do {
$id = '';
for ($i = 0; $i < PASTE_ID_LENGTH; $i++) {
$id .= (string) random_int(0, 9);
}
$stmt = $db->prepare('SELECT 1 FROM pastes WHERE id = ? LIMIT 1');
$stmt->execute([$id]);
} while ($stmt->fetchColumn());
return $id;
}
function baseUrl(): string
{
$https = (
(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ||
(isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443)
);
$scheme = $https ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$path = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? '/'), '/\\');
return $scheme . '://' . $host . ($path === '/' ? '' : $path);
}
function renderPage(string $title, string $body): never
{
?>
= h($title) ?>
= $body ?>
Paste content cannot be empty.'
);
}
if (strlen($content) > MAX_PASTE_LENGTH) {
renderPage(
'Error',
'Paste is too large. The maximum size is 1 MB.
'
);
}
$expiresAt = null;
if ($expiry === 'hour') {
$expiresAt = time() + 3600;
} elseif ($expiry === 'day') {
$expiresAt = time() + 86400;
} elseif ($expiry === 'week') {
$expiresAt = time() + 604800;
} elseif ($expiry === 'month') {
$expiresAt = time() + 2592000;
}
$id = generatePasteId($db);
$stmt = $db->prepare("
INSERT INTO pastes (id, content, created_at, expires_at)
VALUES (?, ?, ?, ?)
");
$stmt->execute([
$id,
$content,
time(),
$expiresAt,
]);
header('Location: ' . baseUrl() . '/' . $id, true, 303);
exit;
}
// Display a paste.
if (preg_match('/^\d{' . PASTE_ID_LENGTH . '}$/', $path)) {
$stmt = $db->prepare('SELECT * FROM pastes WHERE id = ? LIMIT 1');
$stmt->execute([$path]);
$paste = $stmt->fetch();
if (!$paste || ($paste['expires_at'] !== null && (int) $paste['expires_at'] < time())) {
if ($paste) {
$delete = $db->prepare('DELETE FROM pastes WHERE id = ?');
$delete->execute([$path]);
}
http_response_code(404);
renderPage(
'Not found',
'Paste not found or expired.
'
);
}
$expiresText = 'Never';
if ($paste['expires_at'] !== null) {
$expiresText = date('Y-m-d H:i:s T', (int) $paste['expires_at']);
}
$url = baseUrl() . '/' . $paste['id'];
$body = '
Created ' . h(date('Y-m-d H:i:s T', (int) $paste['created_at'])) . '
ยท Expires ' . h($expiresText) . '
' . h($paste['content']) . '
';
renderPage('Paste ' . $paste['id'], $body);
}
// New paste form.
renderPage(
'New paste',
'
'
);