PHP
How a plain PHP site embeds droplets: the page fetches its fragments with curl and prints them into the template.
The pattern in PHP
Section titled “The pattern in PHP”// app/shop.php (trimmed)function shop_fragments(array $wanted): array{ $headers = ['accept' => 'text/html', 'x-droplet-location' => shop_origin(), 'referer' => shop_origin() . shop_raw_target()]; $cookie = shop_cookie_header(); if ($cookie !== null) { $headers['cookie'] = $cookie; } $requests = []; foreach ($wanted as $key => [$id, $pairs]) { $requests[$key] = ['url' => shop_internal_url() . '/droplets/' . rawurlencode($id) . '?' . shop_build_query($pairs), 'headers' => $headers]; } $responses = http_all($requests); // app/http.php: curl_multi, CURLOPT_FOLLOWLOCATION => false
$results = []; foreach ($wanted as $key => [$id]) { $response = $responses[$key]; $status = $response['status'] ?: 502; $result = ['html' => '', 'status' => $status, 'location' => null, 'cookies' => $response['headers']['set-cookie'] ?? [], 'link' => http_header($response, 'link')]; $is_html = str_starts_with((string) http_header($response, 'content-type'), 'text/html'); if ($status >= 300 && $status < 400) { $result['location'] = http_header($response, 'location'); } elseif ((($status >= 200 && $status < 300) || $status === 500) && $is_html) { $result['html'] = $response['body']; $results[$key] = $result; continue; } // … anything else: $result['html'] becomes a "droplet is unavailable" note $results[$key] = $result; } return $results;}<!-- app/views/shop/layout.php, in <head>: once per page --><script type="module" src="/index.js"></script><!-- app/views/shop/gallery.php: the fragment's HTML, as it came --><aside><?= $fragments[0] ?></aside>shop_fragments()sendsGET /droplets/<id>?<params>for every fragment at once toSHOP_INTERNAL_URL, withaccept: text/htmlandx-droplet-locationset toshop_origin(), the origin ofSHOP_PUBLIC_URL. It passes on the browser’sCookiecut down to the shop’s owncart_idandshop_admin, and the page’s URL asreferer:shop_origin()plusshop_raw_target(), the path and query as the browser sent them ($_SERVER['REQUEST_URI']).- curl never follows a redirect, so a droplet’s 3xx is kept:
shop_render()answers it with aLocationheader, and sends the fragments’Set-Cookiewith the page. - Only a
text/htmlanswer (a 2xx, or a 500 carrying the droplet’s error page) is pasted;<?= ?>prints it unescaped. app/views/shop/layout.phploads/index.jsonce.shop_is_proxied()sends/index.js,/env.js,/index.css,/droplets/*,/assets/*and/api/*toshop_proxy(), which passes them on to the shop.
The shop demo, recorded
Section titled “The shop demo, recorded”The shop demo on plain PHP 8.3, recorded by the end-to-end test. How the pieces fit has the diagram.
No framework and no Composer: PHP files on the official php:8.3-apache
image, and curl, which the image already has. Apache sends every path that
is not a file in public/ to public/index.php; the shop’s pages and its
proxy are examples/hosts/php/app/shop.php, the curl helper app/http.php,
the templates app/views/shop/.
Pieces and ports
Section titled “Pieces and ports”docker-compose.yml starts three services:
| Service | Port | What it is |
|---|---|---|
web |
8009, public (Apache on 80 inside) | PHP: the shop’s pages, the proxy, and the basic page at / |
shop |
8300, internal only | the shop’s droplets server (examples/shop) |
droplets |
8000, public | the Svelte example’s droplets server, for / only |
On web |
Value | Used for |
|---|---|---|
SHOP_INTERNAL_URL |
http://shop:8300 |
internal: fragment fetches and the proxy |
SHOP_PUBLIC_URL |
http://localhost:8009 |
public: this host’s own origin, sent as x-droplet-location |
DROPLETS_INTERNAL_URL, DROPLETS_PUBLIC_URL |
http://droplets:8000, http://localhost:8000 |
the same pair, for the basic page |
The official image passes the container’s environment to PHP, so
getenv() reads them. Behind php-fpm, set them with env[…] in the pool
or SetEnv in Apache.
How a page gets a droplet
Section titled “How a page gets a droplet”Each page’s fragments, the toasts and the header’s cart badge included, go
out at once with curl_multi. The fetch is shop_fragments() and the view
is app/views/shop/gallery.php, both shown in the pattern above; the
fragments’ Link preloads go into <head>. The /gallery route asks for
its two:
shop_render('gallery', 'Gallery', '/gallery', [['product-filter', $query], ['product-library', $query]]);referer is the page’s URL, query included. The shop’s handle reads it
with hostFrom, so it is the droplet’s
host, and after
a form posted without JavaScript its query carries the form’s result.
app/views/shop/layout.php loads <script type="module" src="/index.js">
once, through the proxy, and each droplet hydrates itself. The toast-center
fragment comes first in its body; /index.js installs
window.shopMessageQueue before any droplet starts (the shop’s
src/hooks.client.ts):
<body class="shop"><?= $toasts ?><header class="shop-header">…<div class="shop-cart"><?= $cart ?></div>…</header>The pages, GET and HEAD only, are /gallery (the whole query to
product-filter and product-library), /product/<slug> (slug and v to
product-page; order, page, showing and productId to
product-comments), /cart (the cart as variant=inline), /login
(next) and /admin (view and id). The product page first reads the
product from the shop’s public GET /droplets/product-page/_data?slug=<slug>;
an unknown slug renders not-found with 404. Every page and redirect is
sent Cache-Control: private, no-store: its fragments were rendered with
the visitor’s cookies.
What it proxies
Section titled “What it proxies”function shop_is_proxied(string $path): bool{ return preg_match('#^/(?:index\.js$|env\.js$|index\.css$|(?:droplets|assets|api)/)#', $path) === 1;}shop_route() checks it first, for every method, before any page route:
/index.js, /env.js, /index.css, /droplets/* (fragments, _data, form actions), /assets/*
and /api/* go to shop_proxy(). It passes the request on with
x-droplet-location written out and only these of the browser’s headers:
accept, accept-language, content-type, if-none-match, origin,
referer, user-agent, x-droplet-props and x-droplets-build, plus
cookie cut down to the shop’s own cart_id and shop_admin, so another
app’s cookie on this origin stays here. The body is php://input as it
came, and the target is REQUEST_URI concatenated onto
SHOP_INTERNAL_URL, never resolved, so //elsewhere stays a path on the
shop; a path with a . or .. segment, once decoded, is refused with
400. A shop that does not answer within 15 seconds is
502 The shop is unreachable. The answer comes back with its status, every
Set-Cookie and any redirect untouched, and without the per-hop headers
(Connection and what it names, Keep-Alive, Transfer-Encoding,
Upgrade and the rest), nor Content-Length and Content-Encoding, which
no longer hold once curl has decoded the body. The shop’s cookies are
first-party, and nothing is cross-origin; the shop sets them only from form
actions and /api, which come through here.
Gotchas
Section titled “Gotchas”- PHP parses multipart posts into
$_POSTand$_FILESand leavesphp://inputempty, which would lose the admin’s image upload on its way through the proxy.php.initurnsenable_post_data_readingoff: the host never reads a form itself, and every body stays inphp://input. - No cookie jar. No curl handle has
CURLOPT_COOKIEFILE,CURLOPT_COOKIEJARor a share handle, and each lives for one request: aSet-Cookiefrom one visitor’s answer is never sent with another’s. What goes out is the browser’s ownCookie, cut down tocart_idandshop_admin. (A long-running PHP server that reuses handles across requests must keep it that way.) $_GETmerges repeated keys and renamesa.btoa_b. The shop’s pages readQUERY_STRINGthemselves (shop_query()) and pass the pairs on as they came.<?= ?>does not escape. That is how the fragments are pasted; the templates escape everything else withh(). See For hosts.public/is the document root, soapp/is never served, andFallbackResourceroutes any method toindex.phpwithREQUEST_URIas the browser sent it.AllowEncodedSlashes NoDecodelets a%2Fin a path reach PHP instead of a404from Apache.
Run it
Section titled “Run it”cd examples/hosts/phpdocker compose up --buildopen http://localhost:8009/gallery # log in as admin / dropletsSet SHOP_SECRET and DROPLETS_SECRET first; compose refuses to start
without them. The shop trusts one origin besides its own,
DROPLETS_TRUSTED_ORIGINS: http://localhost:8009, this host’s; the rest of
its environment is the same on every host: see
Running a host.
The Svelte example
Section titled “The Svelte example”The same app serves the Svelte example at / (GET and HEAD): its three
droplets, one per mode, from examples/frameworks/svelte (the droplets
service), all three fetched at once.
$droplets_internal = rtrim(getenv('DROPLETS_INTERNAL_URL') ?: 'http://localhost:8000', '/');$droplets_public = rtrim(getenv('DROPLETS_PUBLIC_URL') ?: 'http://localhost:8000', '/');… $who = isset($_GET['who']) && is_string($_GET['who']) ? $_GET['who'] : 'PHP'; $ids = ['client', 'ssr-hydrate', 'ssr-nohydrate']; $responses = http_all(array_map(static fn(string $id) => [ 'url' => $droplets_internal . '/droplets/' . rawurlencode($id) . '?' . http_build_query(['who' => $who]), 'headers' => ['accept' => 'text/html', 'x-droplet-location' => $droplets_public], ], $ids), 5); $fragments = []; foreach ($ids as $index => $id) { $response = $responses[$index]; // Only an HTML answer is a fragment (a 500 carries the droplet's error // page); anything else may echo the props, so it is never pasted. $status = $response['status']; $is_html = str_starts_with((string) http_header($response, 'content-type'), 'text/html'); $fragments[] = (($status >= 200 && $status < 300) || $status === 500) && $is_html ? $response['body'] // trusted markup from the droplets server; never escaped : sprintf('<p class="error">droplet "%s" unavailable: %s</p>', h($id), $status ? 'HTTP ' . $status : 'unreachable'); }<script type="module" src="<?= h($droplets_public) ?>/index.js"></script>…<?php foreach ($fragments as $fragment): ?> <?= $fragment ?><?php endforeach; ?>Here the page loads /index.js from the droplets server’s public URL,
another origin than the page, so the Svelte example runs with cors: true
and DROPLETS_TRUSTED_ORIGINS lists both DROPLETS_URL and this host’s
WEB_URL.
Laravel, Symfony or any other PHP framework works the same way: fetch in
the controller (Guzzle’s Pool or Symfony’s HttpClient run several at
once), print the body unescaped ({!! $fragment !!} in Blade, |raw in
Twig).



