show_esempi.php
<?php
declare(strict_types=1);
// Nome esempio: solo caratteri sicuri (nessun metacarattere di shell, nessun path).
$rawPage = (string)($_GET["page"] ?? '');
$page = preg_match('/^[A-Za-z0-9_]+$/', $rawPage) === 1 ? $rawPage : '';
$safePage = htmlspecialchars($page, ENT_QUOTES, 'UTF-8');
$head = '<!doctype html>
<html lang="it">
<head>
<title>Esempio: ' . $safePage . '</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-3">';
$tail = '</main></body>
</html>';
$path = dirname((string)$_SERVER["SCRIPT_FILENAME"]);
$path .= "/esempi";
chdir($path);
$htmlpage = $page . ".html";
$errore = -1;
if ($page !== '' && file_exists($page)) if ((!file_exists($htmlpage)) or filemtime($page) != filemtime($htmlpage)) {
// Host validato (solo hostname/porta) e tutti gli argomenti passati con
// escapeshellarg(): nessuna shell injection possibile da $page né da Host.
$rawHost = (string)($_SERVER["HTTP_HOST"] ?? '');
$host = preg_match('/\A[A-Za-z0-9.-]+(:[0-9]+)?\z/', $rawHost) === 1 ? $rawHost : 'localhost';
$url = dirname((string)$_SERVER["SCRIPT_NAME"]) . '/simplesso.php';
$errore = 1;
$html = array();
$cmd = escapeshellarg($path . "/prova_simplesso")
. ' ' . escapeshellarg($host)
. ' ' . escapeshellarg($url)
. ' ' . escapeshellarg($page);
exec($cmd, $html, $return_value);
if ($return_value == 0) touch($htmlpage, (int)filemtime($page));
else $errore = 1;
}
switch ($errore) {
case -1:
if ($page === '' || !file_exists($htmlpage)) $html = $head . "<h1>ERRORE: parametri errati o esempio '" . $safePage . "' inesistente.</h1>" . $tail;
else $html = implode('', file($htmlpage) ?: []);
break;
case 0:
$html = implode('', file($htmlpage) ?: []);
break;
case 1:
$html = $head . "<h1>ERRORE: 'prova_simplesso' non può essere eseguito o non riesce a terminare regolarmente.</h1>" . $tail;
break;
}
print $html;