Menu
Learn
Overview Introduction 50 Dimensions Tutorial Snippets vs Other Languages
Build
Editor Playground Compiler API
Docs
Language Spec Formats u keyword Dataframe Python AI Library Feature Status Packages What's Implemented
Platform
Server About Transpilation Web & Templates
Safebox
Why U Analysis Engine Comparison Possibilities
Overview Pipeline Transpiler SAPI PhpCompat Migration Frameworks Performance

PHP on the U WebServer

Drop PHP files in the document root and the U WebServer runs them — no PHP interpreter required. PHP is transpiled to U, compiled to native code, and executed as a shared library, on demand.

U WebServer → About Transpilation

How it works

The U WebServer handles .php files through a transpile-compile-execute pipeline. There is no PHP interpreter in the loop — the server compiles PHP to native machine code through U as an intermediate language.

When a request arrives for a .php file, the server transpiles it to U, compiles the U to C via u2c, compiles the C to a shared library via gcc, and loads it with dlopen. The compiled .so is cached by source mtime — subsequent requests execute the cached binary directly. Source changes trigger automatic recompilation.

1,194PhpCompat functions
11Klines in PhpCompat.u
61PhpSAPI functions
3,104lines in transpiler

The Pipeline

Four stages, fully automatic. The first request compiles; every request after that runs native code.

.phpsource file
→
TranspilerPHP → U
→
u2cU → C
→
gccC → .so
→
dlopenload & call
// What happens internally (php_handler.u) // 1. Transpile: PHP → U via transpilers/cli.js (or tools/php2u.py fallback) // The transpiler rewrites PHP globals to use the explicit SAPI parameter: // header("X: Y") → sapi.queue_header("X: Y") // $_POST["name"] → sapi.post.get("name") // 2. Compile: U → C via u2c, then C → .so via gcc -shared -fPIC -O2 // 3. Load: dlopen the .so, dlsym the handler function // 4. Execute: PhpSAPI.from_request(req) → handler(req, sapi) → sapi.finalize()

The transpiler is available in two implementations: a JS version (transpilers/php-to-u.js, 3,104 lines) and a Python fallback (tools/php2u.py). The server auto-detects which is available and prefers the JS version when node is on the path.

The PHP Transpiler

A source-to-source compiler that translates PHP syntax to U. Handles classes, closures, type annotations, ternaries, array destructuring, and PHP's implicit type coercions.

🔄

Superglobal rewriting

PHP's $_GET, $_POST, $_SERVER, $_SESSION, $_COOKIE are rewritten to sapi.get, sapi.post, etc. — explicit parameters instead of mutable globals, so the server can handle multiple requests in one process.

🎯

Function mapping

PHP builtins map to U stdlib: strlen → .len, json_encode → JSON.encode, array_map → .map. Functions without a stdlib equivalent call into PhpCompat, which implements the exact PHP behaviour.

🔧

Truthiness guards

PHP's loose truthiness (0, "", [] are falsy) differs from U's type-strict booleans. The transpiler wraps conditions in _ensureBool() to preserve PHP semantics in conditional and loop guards.

🔒

Nullable inference

The transpiler tracks which variables may hold null and adds U's +N modifier. Nullable access uses ?. (safe navigation) or guard blocks to match PHP's implicit null handling.

⚙️

Mutability tracking

PHP variables are mutable by default; U variables are immutable. The transpiler detects reassignment and adds +M modifiers to variables that are written after their initial binding.

📦

PSR-4 autoloading

PHP's use and namespace declarations are resolved to U's o imports. PSR-4 class autoloading is mapped to static imports at transpile time — no runtime class loader needed.

The SAPI Layer

PhpSAPI provides the per-request context that PHP code expects: headers, output buffering, sessions, cookies — without mutable global state.

// PhpSAPI.u — 871 lines, 61 functions // Created per-request, passed explicitly to the handler // PhpSAPI.from_request(req) creates the context: // sapi.get — parsed query string ($_GET) // sapi.post — parsed POST body ($_POST) // sapi.cookie — parsed cookies ($_COOKIE) // sapi.server — server vars ($_SERVER) // sapi.files — uploaded files ($_FILES) // sapi.session — session data ($_SESSION) // Output functions map to SAPI methods: // header("X: Y") → sapi.queue_header("X: Y") // setcookie(...) → sapi.set_cookie(...) // session_start() → sapi.session_start() // echo "hello" → sapi.write("hello") // http_response_code() → sapi.set_status() // sapi.finalize() collects output + headers → HttpResp

This explicit-SAPI design is what makes it possible for the U WebServer to handle multiple PHP requests in one process without forking. Each request gets its own PhpSAPI instance — no shared mutable state, no globals, no request leakage.

PhpCompat Library

1,194 functions across 10,992 lines that reproduce PHP's standard library in native U. Not shims or stubs — real implementations with PHP-correct semantics.

The PhpCompat module is organized by category. Each function implements the exact PHP behaviour: array_merge renumbers integer keys, substr accepts negative offsets, sprintf handles all format specifiers.

Filesystem predicates file_exists, is_dir, is_file, …
Path helpers basename, dirname, realpath, …
Multibyte strings mb_strlen, mb_substr, mb_strpos, …
Character classes ctype_alpha, ctype_digit, …
String transforms ucfirst, lcfirst, str_pad, …
String builtins explode, implode, str_replace, …
Math abs, ceil, floor, round, pow, …
Random rand, mt_rand, random_int, …
Type checks is_array, is_string, is_numeric, …
Array functions array_merge, array_keys, in_array, …
Date/Time date, time, strtotime, mktime, …
JSON json_encode, json_decode
Regex preg_match, preg_replace, …
Encoding base64, urlencode, rawurlencode, …
Crypto md5, sha1, hash, hash_hmac, …
cURL curl_init, curl_setopt, curl_exec, …
GD (image) imagecreate, imagecolorallocate, …
PDO (database) PDO, PDOStatement, transactions
OpenSSL openssl_encrypt, X.509, PKCS, …
Sodium sodium_crypto_*, key derivation
Compression gzencode, gzdecode, zlib, …
XML SAX, XMLWriter, SimpleXML, DOM
HTML encoding htmlentities, htmlspecialchars, …
DNS / Network gethostbyname, checkdnsrr, …
IPC shmop, semaphores, msg queues
Sockets socket_create, socket_connect, …
Gettext (i18n) gettext, ngettext, textdomain, …
Fileinfo finfo, MIME detection
EXIF exif_read_data, thumbnails
SPL / Reflection spl_autoload_register, …
Error handling set_error_handler, trigger_error, …
OPcache no-op in compiled code

Migration Path: PHP → U

You don't have to migrate all at once. The U WebServer runs .php and .u files side by side, so you can convert endpoints one at a time.

ApproachWhat changesBinary sizeEffort
Keep PHPNothing. Drop files in, server transpiles them.Includes PhpCompat + PhpSAPIZero
Mixed .php + .uNew endpoints in U, old ones stay PHP.MixedIncremental
Pure .uAll handlers are native U. No PHP layer.Smallest (tree-shaken)Full rewrite

A native .u handler is simpler than a PHP file because it doesn't need the SAPI layer. It receives an HttpReq and returns an HttpResp directly:

// PHP version (api/hello.php) <?php header('Content-Type: application/json'); $name = $_GET['name'] ?? 'world'; echo json_encode(['hello' => $name]); // Equivalent U version (api/hello.u) o "./http" f handle(req: HttpReq) -> HttpResp name = req.query.get("name") ?? "world" r => HttpResp({ status: 200, headers: { "Content-Type": "application/json" }, body: "{\"hello\": \"" + name + "\"}" })

The .u version compiles with -ffunction-sections -fdata-sections and links with --gc-sections, so the resulting shared library contains only the stdlib functions the handler actually calls. A hello-world handler compiles to a few KB.

Framework Support

The transpiler handles real-world PHP patterns: classes with inheritance, traits, interfaces, closures, type annotations, and exception handling.

Qbix Platform

The U WebServer was built to run the Qbix Platform. The PhpCompat library covers Qbix's use of PHP's standard library: sessions, PDO, cURL, image processing (GD), cryptography (sodium/openssl), and the full string/array/math surface. The transpiler handles Qbix's namespace conventions and autoloading.

Laravel / Symfony patterns

PSR-4 autoloading is resolved at transpile time. Namespace declarations and use statements are converted to U's o (import) directives. Type-hinted dependency injection parameters are translated to U struct fields. Laravel-style closures (Route::get('/path', function () { ... })) are translated to U lambdas.

WordPress / procedural PHP

Procedural PHP with global function calls and superglobals is the simplest case for the transpiler. Function-level PHP (add_filter, add_action) maps directly. The main challenge is dynamic include/require with computed paths, which requires the full file set to be known at transpile time.

Performance

Transpiled PHP runs as native code. After the first-request compilation, there is no interpreter, no opcode cache, no JIT warmup — just compiled C.

⚡

First request: compile

The first request to a PHP file triggers transpilation + compilation. This takes a few seconds depending on file size. The compiled .so is cached on disk.

🚀

Subsequent requests: native

After compilation, the server calls the handler through a function pointer — dlsym to find it, then a direct call. No interpreter overhead, no opcode decoding, no garbage collector pauses.

💾

Smart caching

The PhpCache module tracks source mtime. Edit a PHP file and the next request recompiles it automatically. Unchanged files keep using the cached binary indefinitely.

MetricPHP-FPMU WebServer (transpiled PHP)
StartupPHP interpreter + OPcache warmupNative binary, instant
ExecutionZend VM bytecode interpretationCompiled native code
MemoryPHP runtime per-workerShared binary, no interpreter
ConcurrencyOne process per request (FPM)Event loop, shared process
First requestImmediate (interpreted)Compile delay (cached after)