Skip to main content

PHP

An environment-agnostic wrapper around the Emscripten PHP runtime that universals the super low-level API and provides a more convenient higher-level API.

It exposes a minimal set of methods to run PHP scripts and to interact with the PHP filesystem.

Implements

  • Disposable

Index

Properties

optionalrequestHandler

requestHandler?: PHPRequestHandler

semaphore

semaphore: default

An exclusive lock that prevent multiple requests from running at the same time.

Accessors

absoluteUrl

  • get absoluteUrl(): string
  • @deprecated

    Use PHPRequestHandler instead.


    Returns string

documentRoot

  • get documentRoot(): string
  • @deprecated

    Use PHPRequestHandler instead.


    Returns string

Methods

[dispose]

  • [dispose](): void
  • Returns void

addEventListener

  • addEventListener(eventType: request.end | request.error | runtime.initialized | runtime.beforedestroy, listener: PHPEventListener): void
  • Adds an event listener for a PHP event.


    Parameters

    • eventType: request.end | request.error | runtime.initialized | runtime.beforedestroy

      The type of event to listen for.

    • listener: PHPEventListener

      The listener function to be called when the event is triggered.

    Returns void

chdir

  • chdir(path: string): void
  • Changes the current working directory in the PHP filesystem. This is the directory that will be used as the base for relative paths. For example, if the current working directory is /root/php, and the path is data, the absolute path will be /root/php/data.


    Parameters

    • path: string

      The new working directory.

    Returns void

cli

  • cli(argv: string[]): Promise<number>
  • Starts a PHP CLI session with given arguments.

    This method can only be used when PHP was compiled with the CLI SAPI and it cannot be used in conjunction with run().

    Once this method finishes running, the PHP instance is no longer usable and should be discarded. This is because PHP internally cleans up all the resources and calls exit().


    Parameters

    • argv: string[]

      The arguments to pass to the CLI.

    Returns Promise<number>

    The exit code of the CLI session.

defineConstant

  • defineConstant(key: string, value: null | string | number | boolean): void
  • Defines a constant in the PHP runtime.


    Parameters

    • key: string

      The name of the constant.

    • value: null | string | number | boolean

      The value of the constant.

    Returns void

dispatchEvent

  • dispatchEvent<Event>(event: Event): void
  • Type parameters

    Parameters

    • event: Event

    Returns void

exit

  • exit(code?: number): void
  • Parameters

    • code: number = 0

    Returns void

fileExists

  • fileExists(path: string): boolean
  • Checks if a file (or a directory) exists in the PHP filesystem.


    Parameters

    • path: string

      The file path to check.

    Returns boolean

    True if the file exists, false otherwise.

hotSwapPHPRuntime

  • hotSwapPHPRuntime(runtime: number, cwd?: string): void
  • Hot-swaps the PHP runtime for a new one without interrupting the operations of this PHP instance.


    Parameters

    • runtime: number
    • optionalcwd: string

    Returns void

initializeRuntime

  • initializeRuntime(runtimeId: number): void
  • Parameters

    • runtimeId: number

    Returns void

internalUrlToPath

  • internalUrlToPath(internalUrl: string): string
  • @deprecated

    Use PHPRequestHandler instead.


    Parameters

    • internalUrl: string

    Returns string

isDir

  • isDir(path: string): boolean
  • Checks if a directory exists in the PHP filesystem.


    Parameters

    • path: string

      – The path to check.

    Returns boolean

    True if the path is a directory, false otherwise.

isFile

  • isFile(path: string): boolean
  • Checks if a file exists in the PHP filesystem.


    Parameters

    • path: string

      – The path to check.

    Returns boolean

    True if the path is a file, false otherwise.

isSymlink

  • isSymlink(path: string): boolean
  • Checks if a path is a symlink in the PHP filesystem.


    Parameters

    • path: string

    Returns boolean

    True if the path is a symlink, false otherwise.

listFiles

  • Lists the files and directories in the given directory.


    Parameters

    • path: string

      The directory path to list.

    • options: ListFilesOptions = ...

      Options for the listing.

    Returns string[]

    The list of files and directories in the given directory.

mkdir

  • mkdir(path: string): void
  • Recursively creates a directory with the given path in the PHP filesystem. For example, if the path is /root/php/data, and /root already exists, it will create the directories /root/php and /root/php/data.


    Parameters

    • path: string

      The directory path to create.

    Returns void

mkdirTree

  • mkdirTree(path: string): void
  • @deprecated

    Use mkdir instead.


    Parameters

    • path: string

    Returns void

mount

  • Mounts a filesystem to a given path in the PHP filesystem.


    Parameters

    • virtualFSPath: string

      Where to mount it in the PHP virtual filesystem.

    • mountHandler: MountHandler

      The mount handler to use.

    Returns Promise<UnmountFunction>

    Unmount function to unmount the filesystem.

mv

  • mv(fromPath: string, toPath: string): void
  • Moves a file or directory in the PHP filesystem to a new location.


    Parameters

    • fromPath: string
    • toPath: string

    Returns void

onMessage

  • Listens to message sent by the PHP code.

    To dispatch messages, call:

    post_message_to_js(string $data)

    Arguments:
    $data (string) – Data to pass to JavaScript.
    @example
    const php = await PHP.load('8.0');

    php.onMessage(
    // The data is always passed as a string
    function (data: string) {
    // Let's decode and log the data:
    console.log(JSON.parse(data));
    }
    );

    // Now that we have a listener in place, let's
    // dispatch a message:
    await php.run({
    code: `<?php
    post_message_to_js(
    json_encode([
    'post_id' => '15',
    'post_title' => 'This is a blog post!'
    ])
    ));
    `,
    });

    Parameters

    Returns void

pathToInternalUrl

  • pathToInternalUrl(path: string): string
  • @deprecated

    Use PHPRequestHandler instead.


    Parameters

    • path: string

    Returns string

readFileAsBuffer

  • readFileAsBuffer(path: string): Uint8Array
  • Reads a file from the PHP filesystem and returns it as an array buffer.

    @throws

    @php-wasm/universal:ErrnoError – If the file doesn’t exist.


    Parameters

    • path: string

      The file path to read.

    Returns Uint8Array

    The file contents.

readFileAsText

  • readFileAsText(path: string): string
  • Reads a file from the PHP filesystem and returns it as a string.

    @throws

    @php-wasm/universal:ErrnoError – If the file doesn’t exist.


    Parameters

    • path: string

      The file path to read.

    Returns string

    The file contents.

readlink

  • readlink(path: string): string
  • Reads the target of a symlink in the PHP filesystem.


    Parameters

    • path: string

    Returns string

    The target of the symlink.

realpath

  • realpath(path: string): string
  • Resolves the real path of a file in the PHP filesystem.


    Parameters

    • path: string

    Returns string

    The real path of the file.

removeEventListener

  • removeEventListener(eventType: request.end | request.error | runtime.initialized | runtime.beforedestroy, listener: PHPEventListener): void
  • Removes an event listener for a PHP event.


    Parameters

    • eventType: request.end | request.error | runtime.initialized | runtime.beforedestroy

      The type of event to remove the listener from.

    • listener: PHPEventListener

      The listener function to be removed.

    Returns void

request

  • Do not use. Use new PHPRequestHandler() instead.

    @deprecated

    Parameters

    Returns Promise<PHPResponse>

rmdir

  • Removes a directory from the PHP filesystem.


    Parameters

    • path: string

      The directory path to remove.

    • options: RmDirOptions = ...

      Options for the removal.

    Returns void

run

  • Runs PHP code.

    This low-level method directly interacts with the WebAssembly PHP interpreter.

    Every time you call run(), it prepares the PHP environment and:

    • Resets the internal PHP state
    • Populates superglobals ($_SERVER, $_GET, etc.)
    • Handles file uploads
    • Populates input streams (stdin, argv, etc.)
    • Sets the current working directory

    You can use run() in two primary modes:

    Code snippet mode

    In this mode, you pass a string containing PHP code to run.

    const result = await php.run({
    code: `<?php echo "Hello world!";`
    });
    // result.text === "Hello world!"

    In this mode, information like DIR or FILE isn’t very useful because the code is not associated with any file.

    Under the hood, the PHP snippet is passed to the zend_eval_string C function.

    File mode

    In the file mode, you pass a scriptPath and PHP executes a file found at a that path:

    php.writeFile(
    "/www/index.php",
    `<?php echo "Hello world!";"`
    );
    const result = await php.run({
    scriptPath: "/www/index.php"
    });
    // result.text === "Hello world!"

    In this mode, you can rely on path-related information like DIR or FILE.

    Under the hood, the PHP file is executed with the php_execute_script C function.

    The run() method cannot be used in conjunction with cli().

    @example
    const result = await php.run(`<?php
    $fp = fopen('php://stderr', 'w');
    fwrite($fp, "Hello, world!");
    `);
    // result.errors === "Hello, world!"

    Parameters

    Returns Promise<PHPResponse>

setSapiName

  • setSapiName(newName: string): Promise<void>
  • @inheritDoc

    Parameters

    • newName: string

    Returns Promise<void>

setSkipShebang

  • setSkipShebang(shouldSkip: boolean): void
  • Parameters

    • shouldSkip: boolean

    Returns void

setSpawnHandler

  • setSpawnHandler(handler: string | SpawnHandler): Promise<void>
  • Parameters

    Returns Promise<void>

symlink

  • symlink(target: string, path: string): any
  • Creates a symlink in the PHP filesystem.


    Parameters

    • target: string
    • path: string

    Returns any

unlink

  • unlink(path: string): void
  • Removes a file from the PHP filesystem.

    @throws

    @php-wasm/universal:ErrnoError – If the file doesn’t exist.


    Parameters

    • path: string

      The file path to remove.

    Returns void

writeFile

  • writeFile(path: string, data: string | Uint8Array): void
  • Overwrites data in a file in the PHP filesystem. Creates a new file if one doesn’t exist yet.


    Parameters

    • path: string

      The file path to write to.

    • data: string | Uint8Array

      The data to write to the file.

    Returns void