Something went wrong. Try again.
Simple demo of BackflipHTML dual backend / frontend templates
Something went wrong. Try again.
2.7 kB · 102 lines
PHP
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103<?phpdeclare(strict_types=1);
/** * BackflipHTML PHP demo server. * Equivalent to server/index.ts, intended to run under PHP's built-in server: * * php -S 0.0.0.0:8000 server-php/index.php * * Used as a router script: it renders "/" and serves the static asset * directories, returning 404 for everything else. */
require_once __DIR__ . '/vendor/render.php';
$baseDir = __DIR__;
function randomLevel(): int{ return random_int(0, 100);}
$meterNames = [ "Stuff", "Overload", "Allergies", "Hype", "Doomscrolling", "Vibes", "Chaos",];
$meters = array_map( fn(string $name) => ['name' => $name, 'level' => randomLevel()], $meterNames,);
/** * Serve a file from a static directory, mirroring serveDir: resolves the * request path under $fsRoot, guards against path traversal, and sets a * content-type from the extension. Returns true if a response was sent. */function serveStatic(string $fsRoot, string $urlPrefix, string $pathname): bool{ $rel = substr($pathname, strlen($urlPrefix)); $rel = ltrim(rawurldecode($rel), '/');
$root = realpath($fsRoot); if ($root === false) { return false; }
$full = realpath($root . '/' . $rel); // Reject traversal outside the static root or missing files. if ($full === false || !str_starts_with($full, $root . DIRECTORY_SEPARATOR) || !is_file($full)) { return false; }
$types = [ 'css' => 'text/css; charset=utf-8', 'js' => 'text/javascript; charset=utf-8', ]; $ext = strtolower(pathinfo($full, PATHINFO_EXTENSION)); $type = $types[$ext] ?? 'application/octet-stream';
header("Content-Type: $type"); readfile($full); return true;}
function handler(string $pathname): void{ global $baseDir, $meters;
if ($pathname === '/') { $wrapper = backflip_require($baseDir . '/compiled/wrapper.php')['wrapper']; header('Content-Type: text/html; charset=utf-8'); echo '<!DOCTYPE html>'; foreach (backflip_streamRenderRoot($wrapper, ['meters' => $meters]) as $chunk) { echo $chunk; flush(); } return; }
if (str_starts_with($pathname, '/static/')) { if (serveStatic($baseDir . '/../static', '/static/', $pathname)) { return; } } elseif (str_starts_with($pathname, '/static-bfdom/')) { if (serveStatic($baseDir . '/../static-bfdom', '/static-bfdom/', $pathname)) { return; } }
http_response_code(404); header('Content-Type: text/plain; charset=utf-8'); echo 'Not Found';}
$pathname = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';handler($pathname);