scc24php/.hta_404 copy.php

77 lines
2.3 KiB
PHP

<?php
require('.hta_config/env.php');
$requestUri = $_SERVER['REQUEST_URI'];
$slug = getSlug($requestUri);
function getSlug($requestUri) {
$parts = explode('/', $requestUri);
return isset($parts[2]) ? $parts[2] : '';
}
function serveStaticFile($filePath) {
if (file_exists($filePath)) {
echo file_get_contents($filePath);
return true;
}
return false;
}
function fetchFromDatabase($slug, $pdo) {
$stmt = $pdo->prepare("SELECT * FROM `scc24` WHERE `slug` = :slug");
$stmt->bindParam(':slug', $slug, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
function saveToCache($filePath, $content) {
if (!file_put_contents($filePath, $content)) {
error_log("Failed to write cache file: $filePath");
}
}
if (empty($slug)) {
// echo "Slug not provided!";
// exit;
}
$fileName = $slug . ".html";
$filePath = __DIR__ . '/notice/' . $fileName;
ob_start();
$shouldCache = false; // Flag to determine if content should be cached.
if (!serveStaticFile($filePath)) {
try {
$pdo = new PDO("mysql:host=$mariaServer;dbname=$mariaDb", $mariaUser, $mariaPass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$content = fetchFromDatabase($slug, $pdo);
if ($content && isset($content['content']) && $content['content']) {
echo '<div class="container mx-auto">
<div style="padding-top:20px; padding-bottom:15px; font-size:25px;">
<p style="text-align: center;">' . htmlspecialchars($content['title']) . '</p>
</div>
<div>' . $content['content'] . '</div>
</div>';
$shouldCache = true; // Mark content as cacheable.
} else {
echo '<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; margin: 100px 0;"><p style="text-align: center; font-size: 30px; font-weight: bold;">Page not found (404).</p>
<a href="/">Back to home</a>
</div>';
}
} catch (PDOException $e) {
echo "<p class='text-danger'>Error: " . htmlspecialchars($e->getMessage()) . "</p>";
}
}
$htmlContent = ob_get_clean();
// Save to cache only if content was found.
if ($shouldCache) {
saveToCache($filePath, $htmlContent);
}
echo $htmlContent;
?>