Pas de serveur. Juste une page.No server. Just a page.

PHPdans le
navigateur
in the
browser

Compiler l'interpréteur PHP en WebAssembly, et s'en servir pour de vrai.Compiling the PHP interpreter to WebAssembly, and using it for real.

Grégoire Pineau · @lyrixx · JoliCode

🐘
PHP démarre…PHP is starting…

Où tourne PHP ?Where does PHP run?

mon-site.frmy-site.com
📄 php-web.wasm JSphp-web.mjs
GET /page.php → ← <html>…
serveurserver
✕ 🐘

Le navigateur demande. Le serveur exécute PHP, et renvoie du HTML.The browser asks. The server runs PHP, and sends back HTML.

Et si PHP tournait dans la page, sans serveur ?What if PHP ran in the page, with no server?

Deux fichiers statiques, servis comme une image. C'est tout.Two static files, served like an image. That's all.

Ça tourne déjàIt already runs

🐘

emoji-converter

jolicode.github.io/emoji-converter

La lib PHP de JoliCode, dans la page.The PHP lib of JoliCode, in the page.

🔍

composer-diff

lyrixx.github.io/composer-diff

Compare deux composer.lock.Compares two composer.lock.

✍️

JoliTypo

jolitypo.jolicode.com

Corrige la microtypographie d'un texte.Fixes the microtypography of a text.

📝

Symfony Demo

lyrixx.github.io/php-wasm-demo/symfony-demo

La démo officielle, telle quelle.The official demo, as it is.

💿

EasyAdmin

lyrixx.github.io/php-wasm-demo/easyadmin

Le back-office d'un faux disquaire.The back office of a fake record shop.

📘

php.net

php.net/manual · pas sur GitHub Pagesnot on GitHub Pages

Les exemples s'exécutent dans la page.The examples run in the page.

Les cinq premiers sur GitHub Pages : zéro serveur PHPThe first five on GitHub Pages: zero PHP server

Pourquoi faire ça ?Why do that?

♻️

RéutiliserReuse

Une lib PHP qui marche : pas de réécriture en JS.A PHP lib that works: no rewrite in JS.

🔒

Rien ne sortNothing leaves

Les données restent dans le navigateur.The data stays in the browser.

💸

GratuitFree

Un hébergement statique. Rien à maintenir.Static hosting. Nothing to maintain.

🎓

MontrerShow

Playgrounds, docs, démos interactives.Playgrounds, docs, interactive demos.

Le voyageThe journey

De php-src à votre pageFrom php-src to your page

  1. 01WebAssemblyle CPU qui n'existe pasthe CPU that does not exist
  2. 02PHP, du CPHP, in Cet sa prise : la SAPIand its plug: the SAPI
  3. 03CompilerCompileEmscripten, Docker
  4. 04BrancherConnectJS ↔ PHP, octet par octetJS ↔ PHP, byte by byte
  5. 05LivrerShipembarquer, tester, déployerembed, test, deploy
  6. 06Symfonypour de vrai, sans serveurfor real, no server

🐘 L'éléphant en bas de l'écran vous dit où on en est.🐘 The elephant at the bottom of the screen tells you where we are.

01

WebAssembly,
c'est quoi ?
WebAssembly,
what is it?

Le CPU qui n'existe pasThe CPU that does not exist

Un CPU ne parle qu'une langueA CPU speaks one language

add.c
                int add(int a, int b)
                {
                    return a + b;
                }
            
gcc → x86-64 8d 04 37 c3lea eax, [rdi+rsi] · ret 💻 Intel, AMD ✓
gcc → ARM64 00 00 01 0b c0 03 5f d6add w0, w0, w1 · ret 📱 téléphone, Mac Mphone, Apple M ✓
x86-64 sur ARM ?x86-64 on ARM? 8d 04 37 c3« connais pas »“never heard of it” 📱 ✗

Un binaire par CPU. Et par OS.One binary per CPU. And per OS.

WebAssembly : un CPU imaginaireWebAssembly: an imaginary CPU

add.c
                int add(int a, int b)
                {
                    return a + b;
                }
            
emcc→
20 00 20 01 6a 0b
  • 💻 x86-64 ✓
  • 📱 ARM ✓
  • 🍏 Apple M ✓
  • 🖥️ node, serveurnode, server ✓

Au chargement, le navigateur traduit le .wasm dans la langue de votre CPU.On load, the browser translates the .wasm into the language of your CPU.

standard W3C, 2019W3C standard, 2019 tous les navigateurs depuis 2017every browser since 2017 node, Deno, Bun, wasmtime…

À quoi ça ressemble ?What does it look like?

add.c
int add(int a, int b)
{
    return a + b;
}
add.wat · le texteadd.wat · the text
(module
  (func (export "add")
    (param i32 i32)
    (result i32)
    local.get 0
    local.get 1
    i32.add
  ))
add.wasm
…
20 00
20 01
6a
0b

Une instruction = un ou deux octets. Et pas de registres : une stack.One instruction = one or two bytes. And no registers: a stack.

Une stack machineA stack machine

add(2, 40)

local 0 = 2 local 1 = 40
  1. local.get 0push local 0pushes local 0
  2. local.get 1push local 1pushes local 1
  3. i32.addpop deux valeurs, push leur sommepops two values, pushes their sum
  4. endrenvoie le sommet de la stackreturns the top of the stack
2 40 42
la stackthe stack → 42

41 octets. En direct.41 bytes. Live.

const { instance } = await WebAssembly.instantiate(bytes);
instance.exports.add(, )
= ?

Une sandbox ferméeA closed sandbox

module .wasm
⚙️ code
002a000053616c757400
la mémoire : un grand array d'octetsthe memory: a big array of bytes
i32i64f32f64 que des nombres. Pas de string, pas d'objet.only numbers. No string, no object.
📁 fichiersfiles ✗ 🖥️ écranscreen ✗ 🌐 réseaunetwork ✗
JavaScript · l'hôteJavaScript · the host 📁 fichiersfiles ✓ 🖥️ écranscreen ✓ 🌐 réseaunetwork ✓

Écrire, lire un fichier… PHP devra tout demander à JavaScript.Writing, reading a file… PHP will have to ask JavaScript for everything.

02

PHP ?
Un programme C.
PHP?
A C program.

Et sa prise vers le monde : la SAPIAnd its plug to the world: the SAPI

Anatomie de php-srcAnatomy of php-src

SAPI clifpmapache2handlerembed
mainstreams, php.ini, sortie, superglobalesstreams, php.ini, output, superglobals
Zend Enginecompile le PHP en opcodes, et les exécutecompiles PHP to opcodes, and runs them
extensionsstandard · json · pcre · mbstring · dom · intl…
libs CC librarieslibxml2 · oniguruma · ICU · OpenSSL · SQLite

SAPI = Server API : la prise entre PHP et le monde. Qui lui donne la requête ? Où part l'echo ?SAPI = Server API: the plug of PHP to the world. Who gives it the request? Where does echo go?

La SAPI embedThe embed SAPI

PHP, en libPHP, as a library

mon-php.cmy-php.c
                #include <sapi/embed/php_embed.h>
                int main(int argc, char **argv)
                {
                    php_embed_init(argc, argv);
                    zend_eval_string("echo 'Salut';", NULL, "code");
                    php_embed_shutdown();
                }
            
  1. 1 PHP démarrePHP starts
  2. 2 PHP exécute du codePHP runs code
  3. 3 PHP s'arrêtePHP stops
                $ gcc mon-php.c -lphp -o mon-php
                $ ./mon-php
                Salut
            
                $ gcc my-php.c -lphp -o my-php
                $ ./my-php
                Salut
            

Du C… qu'on sait compiler en WebAssembly. 🤔C… that we can compile to WebAssembly. 🤔

03

Compiler PHP
en WebAssembly
Compiling PHP
to WebAssembly

Emscripten, et une chaîne de montage DockerEmscripten, and a Docker assembly line

Emscripten : un faux OS, en JSEmscripten: a fake OS, in JS

hello.c
                    #include <stdio.h>
                    int main(void)
                    {
                        printf("Salut\n");
                    }
                
                $ emcc hello.c -o hello.mjs
                $ node hello.mjs
                Salut
            
hello.wasmle codethe code JShello.mjsla gluethe glue
Linux Emscripten ton codeyour code
hello.cprintf("Salut\n")
hello.c.wasmprintf("Salut\n")
la libcthe libc
glibcwrite(1, …)
musl.wasmwrite(1, …)
le kernelthe kernel
Linuxun syscalla system call
la glue JSthe JS glue.mjsfd_write(1, …)
les fichiersthe files
sur le disqueon the disk
en mémoirein memory.mjsun faux disque, en JSa fake disk, in JS

Sur Linux, printf ne sait pas écrire : la libc demande au kernel.On Linux, printf cannot write: the libc asks the kernel.

Emscripten compile ton code et une vraie libc en .wasm (clang + LLVM).Emscripten compiles your code and a real libc to .wasm (clang + LLVM).

Pas de kernel dans la sandbox : la libc appelle un import de la glue JS.No kernel in the sandbox: the libc calls an import of the JS glue.

fopen() marche aussi : la glue garde les fichiers en mémoire.fopen() works too: the glue keeps the files in memory.

Même build, autre compilateurSame build, another compiler

emconfigure ./configure && emmake make

Ils posent CC=emcc, AR=emar… : ./configure n'y voit que du feu.They set CC=emcc, AR=emar…: ./configure does not notice a thing.

--host=wasm32-unknown-emscriptenon compile pour une autre machinewe compile for another machine
--enable-embed=staticlibphp.a : la SAPI embed: the embed SAPI
--disable-allaucune extension… puis celles qu'on choisitno extension… then the ones we pick
--without-pcre-jitpas de JIT : impossible de générer du code machineno JIT: no way to generate machine code
--disable-fiber-asmpas d'assembleur pour changer de stackno assembly to switch stacks
--disable-cli --disable-cgiles autres SAPI ne servent à rien icithe other SAPIs are no use here

Une extension, une libOne extension, one library

mbstring→oniguruma
dom xml simplexml→libxml2
pdo_sqlite sqlite3→SQLite
openssl→OpenSSL
intl→ICU
gd→libpng · libjpeg-turbo · libwebp
zip zlib→libzip · zlib
sodium→libsodium
php-web.wasm
libsodium libzip · zlib libpng · libjpeg-turbo · libwebp ICU OpenSSL SQLite libxml2 oniguruma libphp.a

Compilées elles aussi avec emcc. Pas de .so, pas de dlopen() : tout dans un seul fichier.Compiled with emcc too. No .so, no dlopen(): all in one file.

docker/Dockerfile

Une chaîne de montageAn assembly line

EXTENSIONS="mbstring dom" EXTENSIONS="mbstring dom intl"
resolvele planthe plan
php-srcgit clone
oniguruma
libxml2
icu
libiconv
openssl
sqlite
zlib
libpng
libjpeg
libwebp
libzip
libsodium
phpconfigure + make
linkemcc → .wasm
📦 php-web.mjs php-web.wasm
compilebuilds rien à fairenothing to do en cachecached

Chaque étape ne lit que son bout du plan : Docker ne refait que ce qui a changé.Each stage reads only its part of the plan: Docker only redoes what changed.

Combien ça pèse ?How big is it?

PHP 8.47,5 Mo 2,8 gzip7.5 MB 2.8 gzip
PHP 8.58,7 Mo 3,0 gzip8.7 MB 3.0 gzip
PHP 8.6 défautdefault8,7 Mo 3,1 gzip8.7 MB 3.1 gzip
tout, sauf ICUall, but ICU19,8 Mo 7,4 gzip19.8 MB 7.4 gzip
Symfony30,6 Mo 7,2 gzip30.6 MB 7.2 gzip
+ intl, ICU41,9 Mo 16,4 gzip41.9 MB 16.4 gzip

32 Mo de données ICU, toutes les langues, en array C avec #embed (C23) :32 MB of ICU data, every language, as a C array with #embed (C23):

            alignas(16) const unsigned char icudt78_dat[] = {
            #embed "data/in/icudt78l.dat"
            };
        

Ce qui ne marche pas (et pourquoi)What does not work (and why)

🔢 Entiers 32 bits🔢 32-bit integers

wasm32 : un long fait 4 octets.wasm32: a long is 4 bytes.


        

🧵 Fibers

WebAssembly ne sait pas suspendre puis reprendre une stack.WebAssembly cannot suspend a stack, then resume it.

Aborted(missing function: getcontext)

🚫 Processus🚫 Processes

Pas d'autre programme à lancer : exec(), proc_open()…No other program to run: exec(), proc_open()…


        

🌐 Réseau🌐 Network

Pas de socket : https:// et ssl:// ne se connectent pas.No socket: https:// and ssl:// do not connect.

04

Parler à PHP
depuis JavaScript
Talking to PHP
from JavaScript

Octet par octetByte by byte

run.c : notre entrypoint: our entry point

docker/run.c, simplifiédocker/run.c, simplified
                int run_code(char *code, int argc, char **argv)
                {
                    php_embed_init(argc, argv);
                    zend_eval_string(code, NULL, "Command line code");
                    int status = EG(exit_status);
                    php_embed_shutdown();
                    return status;
                }
            
                $ emcc run.o libphp.a … -o php-web.mjs \
                    -s EXPORTED_FUNCTIONS=_malloc,_free,_run_code,_run_file,…
            
🚀 démarrestarts ⚙️ exécuteruns 🧹 s'arrêtestops une requêteone request

Rien ne survit d'un appel à l'autre. Comme PHP-FPM.Nothing survives from one call to the next. Like PHP-FPM.

Une string ? Non : un pointeur.A string? No: a pointer.

            const bytes = new TextEncoder().encode(code + '\0');
            const ptr = _malloc(bytes.length);
            HEAPU8.set(bytes, ptr);
            _run_code(ptr, argc, argv);
            _free(ptr);
        

code = "echo 'Salut';"

un pointeur, c'est… un nombre : 1048a pointer is… a number: 1048

côté C, char *code lit à partir de 1048… jusqu'au 00on the C side, char *code reads from 1048… up to the 00

la place est rendue : PHP peut s'en resservirthe space is given back: PHP can use it again

la mémoire du module, HEAPU8 · un octet par casethe memory of the module, HEAPU8 · one byte per cell

char **argv : des pointeurs de pointeurs: pointers to pointers

php.runCode(code, { args: ['un', 'deux'] })php.runCode(code, { args: ['one', 'two'] }) → $argv

argv = 2000 11004c 04 00 00 1200b0 04 00 00 130014 05 00 00
1100"Standard input code\0" 1200"un\0""one\0" 1300"deux\0""two\0"
        const pointers = argv.map(copyString);
        const array = _malloc(pointers.length * 4);
        HEAPU32.set(pointers, array / 4);
    

HEAPU8 et HEAPU32 : deux lunettes sur la même mémoire. Un u32 = 4 octets, à l'envers (little-endian).HEAPU8 and HEAPU32: two lenses on the same memory. A u32 = 4 bytes, backwards (little-endian).

Et dans l'autre sens : echoAnd the other way: echo

PHPecho "Salut";
→
libcwrite(1, …)
→
glue JSJS glueModule.stdout(83)une fois par octetonce per byte
→
JS[83, 97, 108, 117, 116]
Salut
            Module.stdin  = () => stdio.stdin[stdio.read++] ?? null;
            Module.stdout = (byte) => stdio.stdout.push(byte);
            Module.stderr = (byte) => stdio.stderr.push(byte);
        
TextDecoder"Salut"

stdin, à l'envers : PHP demande un octet, JS le donne. null : c'est fini.stdin, the other way around: PHP asks for a byte, JS gives it. null: it is over.

Et tout ça, pour trois lignesAnd all that, for three lines

                import createPhp from './php-web.mjs';

                const php = await createPhp();
                const result = await php.runCode(
                    'echo ucfirst(file_get_contents("php://stdin")), " ", $argv[1];',
                    { stdin: 'salut', args: ['🐘'] },
                );
            
                import createPhp from './php-web.mjs';

                const php = await createPhp();
                const result = await php.runCode(
                    'echo ucfirst(file_get_contents("php://stdin")), " ", $argv[1];',
                    { stdin: 'hello', args: ['🐘'] },
                );
            

runCode() est écrit en JS, et injecté dans le module : emcc --pre-js api.jsrunCode() is written in JS, and injected into the module: emcc --pre-js api.js

{ … }
PHP démarre…PHP is starting…
05

Embarquer son code,
et livrer
Embedding your code,
and shipping

De votre projet à GitHub PagesFrom your project to GitHub Pages

PHP ne voit pas votre disquePHP does not see your disk

  • /
  • tmp/en mémoirein memory
  • app/embarqué · dans le .wasmembedded · in the .wasm
  • src/ · vendor/
  • etc/ssl/openssl.cnfembarquéembedded
  • symfony/IndexedDB

À l'exécutionAt runtime

php.FS.writeFile('/tmp/in.json', data);

Au build : dans le .wasmAt build time: in the .wasm

                    $ composer install --no-dev --classmap-authoritative
                    $ emcc … --embed-file ./build/embed@/app
                

Qui survit au rechargementThat survives a reload

const php = await createPhp({ persist: '/symfony' });

IndexedDB, et un verrou (Web Lock) entre les onglets.IndexedDB, and a lock (Web Lock) between the tabs.

Une stack, une commandeOne stack, one command

stacks.php
                $php86 = Stack::named('php-8.6')
                    ->php('8.6.0')
                    ->extensions('ctype', 'dom', 'mbstring')
                    ->targets(Target::Web, Target::Node);

                return [$php86,
                    $php86->renamed('php-8.6-intl')
                        ->extensions('intl')];
            
                $ castor wasm:build php-8.6-intl
                $ castor wasm:run -r 'echo PHP_VERSION;'
                $ castor wasm:check
                $ castor wasm:serve symfony
            

Stack → bake.json → docker buildx bake

Toutes les stacks en un appel, en parallèle, qui partagent leurs layers.All the stacks in one call, in parallel, sharing their layers.

Dans votre projetIn your project

1
$ castor composer require lyrixx/php-wasm-builder
2
                function wasm_stack(): Stack
                {
                    return Stack::named('app')->extensions('ctype', 'mbstring')
                        ->embed('build/embed', at: '/app')
                        ->targets(Target::Web)->outputDir('public/build');
                }
                // castor wasm:build → build([wasm_stack()])
            
3
                import createPhp from './build/php-web.mjs';
                const { stdout } = await (await createPhp()).runFile('/app/src/page.php');
            
📖 lyrixx.github.io/php-wasm-builder/your-project

Tester, puis déployerTest, then deploy

Le build pour le web tourne aussi dans node :The build for the web runs in node too:

                $ node --import ./node/fetch-files.mjs \
                    --test tests/page.test.mjs
            

fetch() lit les URL file: sur le disque, comme un serveur les servirait.fetch() reads the file: URLs from the disk, as a server would serve them.

  • check_stack() la version, les extensionsthe version, the extensions
  • run_code() du PHP, comme runCode()PHP code, like runCode()
  • test_page() le JS de la pagethe JS of the page
  1. 📤git push
  2. 🐳castor wasm:buildlayers en cache GitHub Actionslayers cached by GitHub Actions
  3. ✅castor wasm:smokeça démarre, ça répond ?does it start, does it answer?
  4. 🚀GitHub Pages

Rien n'est déployé s'il ne répond pas.Nothing is deployed if it does not answer.

06

Un vrai Symfony,
sans serveur
A real Symfony,
no server

Sept problèmes, sept astucesSeven problems, seven tricks

Problème 1 / 7Problem 1 / 7

Premier essai : ça exploseFirst try: it blows up

$ bin/console cache:warmup
RuntimeError: null function or function signature mismatch
la mémoire de PHP : ses objets, ses fonctionsthe memory of PHP: its objects, its functions stack C · 64 KoC stack · 64 KB stack C · 1 MoC stack · 1 MB

PHP se rappelle lui-même, en C : array_map(), usort()… Chaque callback remplit la stack.PHP calls itself back, in C: array_map(), usort()… Each callback fills the stack.

≈ 400 callbacks de profondeur : la stack déborde sur PHP. Sans un mot.≈ 400 callbacks deep: the stack overflows onto PHP. Without a word.

$ emcc … -s STACK_SIZE=1mb -s STACK_OVERFLOW_CHECK=2

Désormais, un stack overflow tue le module, au lieu d'écraser PHP.From now on, an overflow kills the module, instead of crushing PHP.

Problème 2 / 7Problem 2 / 7

Symfony veut une requêteSymfony wants a request

index.php
                    http_response_code(201);
                    setcookie('talk', 'php');
                    printf('%s, %s', PHP_SAPI, $_POST['message']);
                
                const response = await php.request({
                    method: 'POST',
                    url: 'https://mon-site.fr/messages',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'message=Salut',
                }, { documentRoot: '/app/public' });
            
                const response = await php.request({
                    method: 'POST',
                    url: 'https://my-site.com/messages',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'message=Hello',
                }, { documentRoot: '/app/public' });
            
{ … }

in_array(PHP_SAPI,
    ['cli', 'phpdbg', 'embed'], true)

embed y est : Symfony se croit en ligne de commande. Pendant une requête, on renomme la SAPI wasm, qui n'y est pas.embed is in it: Symfony believes it is on the command line. During a request, we rename the SAPI wasm, which is not.

Problème 3 / 7Problem 3 / 7

Un lien, un formulaire… qui répond ?A link, a form… who answers?

🌐navigateurbrowserGET /messages
→
🛂service workervoit chaque requêtesees every request
→
📦GitHub Pages404
🐘PHPphp.request()
        self.addEventListener('fetch', (event) => {
            event.respondWith(serve(event.request));
        });

        async function serve(request) {
            const { status, headers, body } = await php.request({ … });
            return new Response(body, { status, headers });
        }
    

Le serveur web est dans le navigateur.The web server is in the browser.

Problème 4 / 7Problem 4 / 7

PHP travaille, la page gèlePHP works, the page freezes

🐘

1,5 s de PHP : l'éléphant suit ?1.5 s of PHP: does the elephant follow?

                import { createPhpInWorker } from './php-web.mjs';

                const php = await createPhpInWorker();
            

Aucun fichier de plus : php-web.mjs se relance lui-même.No extra file: php-web.mjs starts itself again.

new Worker(import.meta.url, { type: 'module' });

Le piège de Chrome : dans un Web Worker, la stack JS est plus petite. ≈ 1 000 callbacks de profondeur, au lieu de 2 000.The trap of Chrome: in a Web Worker, the JS stack is smaller. ≈ 1,000 callbacks deep, instead of 2,000.

Web Worker ≠ service worker

Alors, PHP tourne où ?So, where does PHP run?

serveInFrame()

Dans un Web WorkerIn a Web Worker

Un thread lancé par la page : il meurt avec elle.A thread started by the page: it dies with it.

🖼️ Symfony s'affiche dans une iframe.🖼️ Symfony shows in an iframe.

  1. iframeenvoie la requêtesends the request
  2. service workerl'intercepteintercepts it
  3. page parenteparent pagela passe au Web Workerhands it to the Web Worker
  4. 🐘 Web WorkerPHP répondPHP answers

serveInServiceWorker()

Dans le service workerIn the service worker

Un proxy devant le réseau, géré par le navigateur.A network proxy, run by the browser.

🌐 Symfony a sa propre page.🌐 Symfony has its own page.

  1. pageenvoie la requêtesends the request
  2. 🐘 service workerl'intercepte, et PHP répondintercepts it, and PHP answers

De vraies URL, l'historique, les rechargements.Real URLs, the history, the reloads.

⏱️ Chrome : 30 s⏱️ Chrome: 30 s

Rien à faire ? Chrome arrête le service worker, et PHP avec. La requête suivante le relance, et IndexedDB garde ses fichiers.Nothing to do? Chrome stops the service worker, and PHP with it. The next request starts it again, and IndexedDB keeps its files.

Problème 5 / 7Problem 5 / 7

Ce que le navigateur cacheWhat the browser hides

🍪 Set-Cookie

Jeté de toute réponse fabriquée par un service worker. Les cookies sont gardés à côté : localStorage, Cache API.Dropped from any response that a service worker makes. The cookies are kept aside: localStorage, the Cache API.

📨 Cookie

Jeté d'une Request. Alors php.request() prend des données, pas une Request.Dropped from a Request. So php.request() takes data, not a Request.

🔗 Referer

Pas un header pour un service worker. On le rend à PHP depuis request.referrer : le CSRF de Symfony le vérifie.Not a header for a service worker. We give it back to PHP from request.referrer: the CSRF of Symfony checks it.

🏘️ *.github.io

Tous vos repos partagent une origine : le service worker ne parle qu'à sa page.All your repositories share one origin: the service worker only talks to its own page.

serveInFrame() et serveInServiceWorker() s'en chargent.serveInFrame() and serveInServiceWorker() handle it.

Problème 6 / 7Problem 6 / 7

1 900 requêtes, et il meurt1,900 requests, and it dies

code, donnéescode, data malloc() → ce que chaque run oubliewhat each run forgets 💥 ← Zend MM · blocs de 2 Mo← Zend MM · blocks of 2 MB

0128 Mo128 MB

PHP tournait avec USE_ZEND_ALLOC=0 : il allouait avec malloc(), comme n'importe quel programme C.PHP ran with USE_ZEND_ALLOC=0: it allocated with malloc(), as any C program.

PHP compte sur son allocateur pour tout jeter à la fin d'une requête. Avec malloc(), ce qu'il oublie reste. La mémoire se remplit.PHP counts on its allocator to throw it all away at the end of a request. With malloc(), what it forgets stays. The memory fills up.

Zend MM, l'allocateur de PHP : des blocs de 2 Mo, pris à la fin de la mémoire. Le run fini, il les rend tous.Zend MM, the allocator of PHP: blocks of 2 MB, taken from the end of the memory. Once the run is over, it gives back all of them.

$stack->ini(['memory_limit' => '64M']);
…

Problème 7 / 7Problem 7 / 7

Lancer PHP… pendant le buildRunning PHP… during the build

examples/symfony/stack.php
                Stack::named('example-symfony')
                    ->extensions('ctype', 'filter', 'iconv', 'mbstring',
                        'pdo_sqlite', 'session', 'tokenizer', 'xml')
                    ->embed(__DIR__ . '/app', at: '/app')
                    ->warmup('bin/console', 'cache:warmup')
                    ->opcache(Opcache::Runtime)
                    ->targets(Target::Web);
            
  1. 🐳L'étape warm du DockerfileThe warm stage of the DockerfilePHP en WebAssembly, dans nodePHP as WebAssembly, in node
  2. 📂/app monté avec NODEFS/app mounted with NODEFSPHP écrit sur le vrai disque, avec les chemins du WASMPHP writes on the real disk, with the paths of the WASM
  3. 📦--embed-filele cache de Symfony finit dans le .wasmthe cache of Symfony ends up in the .wasm

Le démarrage : 600 → 220 ms.The boot: 600 → 220 ms.

Problème 7 / 7, suiteProblem 7 / 7, continued

opcache, sans mémoire partagéeopcache, without shared memory

Un run démarre PHP et l'arrête : ce qu'opcache compile meurt avec lui. Et WebAssembly n'a pas de mémoire partagée.A run starts PHP and stops it: what opcache compiles dies with it. And WebAssembly has no shared memory.

                opcache.file_cache=/opcache
                opcache.file_cache_only=1
            

Les opcodes vont dans des fichiers, que les runs suivants lisent.The opcodes go in files, that the next runs read.

  • Ce qui est embarqué date du 1970-01-01 00:00:01 : caché dès le premier run.What is embedded dates from 1970-01-01 00:00:01: cached from the first run.
  • Deux bugs de PHP, corrigés dans PHP 8.5.13 : php-src#24184, #24745.Two bugs of PHP, fixed in PHP 8.5.13: php-src#24184, #24745.
  • Un troisième, contourné dans run.c : #25195.A third one, worked around in run.c: #25195.
sans opcacheno opcache…compile à chaque runcompiles on each run
1er run1st run…compile, et écrit dans /opcachecompiles, and writes in /opcache
2e run2nd run…lit /opcachereads /opcache

Ce que ça changeWhat it changes

DémarrageBoot 1re requêteFirst request Requêtes suivantesNext requests TéléchargementDownload
riennothing 600 ms 250 ms 115 ms 7,4 Mo7.4 MB
WARMUP 220 ms 160 ms 110 ms 7,5 Mo7.5 MB
WARMUP + runtimel'exemplethe example 410 ms 245 ms 35 ms 7,5 Mo7.5 MB
WARMUP + precompiled 135 ms 75 ms 35 ms 19 Mo19 MB

L'exemple Symfony, mesuré dans node. Téléchargement : le .wasm, gzippé.The Symfony example, measured in node. Download: the .wasm, gzipped.

46 Mo d'opcodes pour 16 Mo de PHP.46 MB of opcodes for 16 MB of PHP.

Le livre d'or de l'exemple Symfony

Symfony. En direct.Symfony. Live.

  1. Écrire un messageWrite a message
  2. Recharger : il est toujours làReload: it is still there
  3. Aucun serveur PHPNo PHP server

Sur votre téléphone :On your phone:
lyrixx.github.io/php-wasm-builder/examples/symfony

Cloudflare Worker

Et de retour sur un serveurAnd back on a server

worker.mjs
                import createPhp from './build/php-web.mjs';
                import phpWasm from './build/php-web.wasm';

                let php;
                export default {
                    async fetch(request) {
                        php ??= createPhp({ instantiateWasm … });
                        const { status, headers, body } =
                            await (await php).request({ … });

                        return new Response(body, { status, headers });
                    },
                };
            
  1. 📦Le même php-web.mjsThe same php-web.mjsle build pour le web, tel quelthe build for the web, as it is
  2. 🧠->memory('64mb')128 Mo pour le module et JavaScript, ensemble128 MB for the module and JavaScript, together
  3. ⏱️10 ms de CPU par requête10 ms of CPU per requestplan gratuit · une API d'audit : 37 ms, en médianeFree plan · an audit API: 37 ms, the median

Compilé pour le navigateur… et ça répond à curl.Compiled for the browser… and it answers curl.

À vous de jouerYour turn

PHP démarre…PHP is starting…

            

Récap : du C à votre pageRecap: from C to your page

  1. php-src+ libxml2, ICU…
  2. emconfigureemmakecompilés pour wasm32compiled for wasm32
  3. libphp.arun.cla SAPI embedthe embed SAPI
  4. emcc --pre-js api.jsle linkthe link
  5. php-web.wasmphp-web.mjsdeux fichiers statiquestwo static files
  6. runCode()request()pointeurs, octets… et Symfonypointers, bytes… and Symfony

🐘 PHP, dans la page. Sans serveur.🐘 PHP, in the page. No server.

Merci 🐘Thanks 🐘

lyrixx.github.io/php-wasm-builder

github.com/lyrixx/php-wasm-builder

Le builder d'origine : Derick Rethans, pour la PHP Foundation.
run.c vient du travail d'Antoine Bluchet (soyuka) sur PHP en WebAssembly.
The original builder: Derick Rethans, for the PHP Foundation.
run.c comes from the work of Antoine Bluchet (soyuka) on PHP in WebAssembly.

Questions ?Questions?