templates/php-app/public/index.php
2026-11-28 15:28:02 +02:00

87 lines
2.9 KiB
PHP

<?php
// A small PHP site with no dependencies: a home page, a contact form that
// checks its fields, and a health check. Works on PHP 7.4 and 8.x.
declare(strict_types=1);
$tz = getenv('TZ') ?: 'UTC';
if (!@date_default_timezone_set($tz)) {
date_default_timezone_set('UTC');
}
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
if ($path === '/health') {
header('Content-Type: application/json');
echo json_encode(['status' => 'ok']);
exit;
}
if ($path !== '/') {
http_response_code(404);
header('Content-Type: text/plain; charset=utf-8');
echo "Page not found\n";
exit;
}
function e(string $s): string
{
return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$siteName = getenv('SITE_NAME') ?: 'My business';
$sent = false;
$errors = [];
$name = '';
$email = '';
$message = '';
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
$name = trim((string) ($_POST['name'] ?? ''));
$email = trim((string) ($_POST['email'] ?? ''));
$message = trim((string) ($_POST['message'] ?? ''));
if ($name === '' || mb_strlen($name) > 100) {
$errors[] = 'Please write your name.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Please write a valid email address.';
}
if ($message === '' || mb_strlen($message) > 5000) {
$errors[] = 'Please write a message (up to 5000 characters).';
}
if (!$errors) {
// Send or store the message here, for example through your email API.
$sent = true;
$name = $email = $message = '';
}
}
header('X-Content-Type-Options: nosniff');
?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= e($siteName) ?></title>
<style>
body { font: 17px/1.6 system-ui, sans-serif; max-width: 40rem; margin: 3rem auto; padding: 0 1rem; }
label { display: block; margin-top: 1rem; }
input, textarea { width: 100%; padding: .5rem; font: inherit; }
button { margin-top: 1rem; padding: .6rem 1.2rem; font: inherit; }
.ok { color: #157f3b; } .err { color: #b42318; }
</style>
</head>
<body>
<h1><?= e($siteName) ?></h1>
<p>The PHP site is running (PHP <?= e(PHP_VERSION) ?>, <?= e(date('Y-m-d H:i')) ?>). Edit <code>public/index.php</code> to build on it.</p>
<h2>Contact us</h2>
<?php if ($sent): ?><p class="ok">Thank you. We got your message.</p><?php endif; ?>
<?php foreach ($errors as $err): ?><p class="err"><?= e($err) ?></p><?php endforeach; ?>
<form method="post" action="/">
<label>Name <input name="name" maxlength="100" required value="<?= e($name) ?>"></label>
<label>Email <input name="email" type="email" required value="<?= e($email) ?>"></label>
<label>Message <textarea name="message" rows="5" maxlength="5000" required><?= e($message) ?></textarea></label>
<button type="submit">Send</button>
</form>
</body>
</html>