show_src.php
<?php
declare(strict_types=1);
// Solo il nome file, senza componenti di path: nessun path traversal.
$requested = basename((string)($_GET['script'] ?? ''));
$safeName = htmlspecialchars($requested, ENT_QUOTES, 'UTF-8');
$allowedExt = ['php', 'inc', 'c', 'cpp', 'h', 'hpp'];
$ext = strtolower(pathinfo($requested, PATHINFO_EXTENSION));
$dir = __DIR__;
$fullPath = $dir . '/' . $requested;
$realPath = realpath($fullPath);
$error = null;
$source = null;
if ($requested === '') {
$error = 'Nome dello script mancante.';
} elseif (!in_array($ext, $allowedExt, true)) {
$error = 'Sono ammessi solo file di codice sorgente (' . implode(', ', $allowedExt) . ').';
} elseif ($realPath === false || !str_starts_with($realPath, $dir . '/') || !is_file($realPath) || !is_readable($realPath)) {
$error = 'File non trovato.';
} else {
$source = (string)file_get_contents($realPath);
}
?>
<!doctype html>
<html lang="it">
<head>
<title>Sorgente di "<?= $safeName ?>"</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-body-tertiary">
<main class="container py-4">
<div class="card shadow-sm">
<div class="card-body">
<?php if ($error !== null): ?>
<h1 class="h4 text-center mb-3 text-danger">ERRORE: <?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></h1>
<?php else: ?>
<h1 class="h4 text-center mb-3"><?= $safeName ?></h1>
<pre class="border rounded p-3 bg-light"><code><?= htmlspecialchars((string)$source, ENT_QUOTES, 'UTF-8') ?></code></pre>
<?php endif; ?>
</div>
</div>
</main>
</body>
</html>