Io\Terminal View as Markdown

Under discussion
▴ 14 ▾ 0
community vote
Authors
Pratik Bhujel, prateekbhujelpb@gmail.com
Date
2026-09-27
Version
0.6
Target
PHP 8.7
Implementation
https://github.com/php/php-src/pull/23941
Source
wiki.php.net/rfc/io_terminal

Vote

Implement Io\Terminal for PHP 8.7 as outlined in the RFC? no votes
Yes · No · Abstain

Discussions on the mailing list

[Discussion] Native terminal helpers for PHP CLI
by Pratik Bhujel · 4 messages
[PHP DEV] [Discussion] Native terminal helpers for PHP CLI
by Pratik Bhujel · 2 messages
[PHP DEV] [Discussion] Native terminal helpers for PHP CLI
by Pratik Bhujel · 2 messages
[PHP DEV] [Discussion] Native terminal helpers for PHP CLI
by Pratik Bhujel · 6 messages
[RFC] Io\Terminal
by Pratik Bhujel · 38 messages

RFC text

Copied from wiki.php.net, last synchronized Nov 9, 2026 05:46 UTC

Introduction

Command-line applications often need to read a key without waiting for Enter, ask for a password without echoing it, or find out how much space is available in the terminal. PHP can read from streams, but it does not currently provide the same set of native terminal operations on POSIX systems and Windows.

This RFC proposes an Io\Terminal API in ext/standard. It provides terminal size queries, raw-mode management, key input, line input, and hidden input. It is intended both for small scripts and for libraries that need terminal operations without relying on platform-specific commands.

For example, a script can check the size and wait for a key:

<?php
 
use Io\Terminal\Key;
use Io\Terminal\Terminal;
use Time\Duration;
 
$terminal = Terminal::fromStdio();
 
$dimensions = $terminal->getDimensions();
if ($dimensions !== null) {
    printf("%d columns, %d rows\n", $dimensions->cols, $dimensions->rows);
}
 
$key = $terminal->readKey(Duration::fromSeconds(5));
if ($key === Key::Escape) {
    echo "Escape pressed\n";
}

Motivation

Terminal libraries already provide prompts, menus, and other interactive interfaces in userland. The difficulty is in the operations beneath them. On POSIX, a library may run stty to save and change terminal settings or find the terminal size. Windows uses a different console API, so the same approach is not portable.

For example, Laravel Prompts uses stty to save and restore the terminal mode. Symfony Console can use stty on POSIX and mode CON on Windows to determine the terminal size. A native API would let libraries perform these operations without starting an external command. It would also give applications one way to request raw mode and restore it when they are finished.

The implementation has also been tried with phasync/tui. Its maintainer replaced the library's stty calls for raw mode and sizing with the proposed API and reported the same test results as on stock PHP, including pseudo-terminal restoration tests. He also proposed a smaller scope for this RFC; that suggestion remains part of the discussion.

The aim is not to put a terminal UI framework or a line editor in PHP. The parts that need native support are raw mode, restoring the previous mode, and the terminal size. This RFC provides those, together with key, line, and hidden input for scripts that do not want a library. Prompts, menus, line editors, and full-screen interfaces stay in userland and can be built on top; see “To the ecosystem” below. The RFC does not provide a general input-event API with modifiers, mouse input, or paste.

Proposal

The following classes and enum are added:

<?php
 
namespace Io\Terminal {
 
    /** @strict-properties */
    class TerminalException extends \Io\IoException {}
 
    enum Key
    {
        case Up;
        case Down;
        case Right;
        case Left;
        case Enter;
        case Backspace;
        case Escape;
        case Tab;
        case Home;
        case End;
        case Delete;
        case Insert;
        case PageUp;
        case PageDown;
        case Resize;
        case ShiftTab;
        case F1;
        case F2;
        case F3;
        case F4;
        case F5;
        case F6;
        case F7;
        case F8;
        case F9;
        case F10;
        case F11;
        case F12;
    }
 
    /** @strict-properties */
    final readonly class Dimensions
    {
        public readonly int $cols;
        public readonly int $rows;
 
        public function __construct(int $cols, int $rows) {}
    }
 
    /**
     * Destroying the last reference to an active token attempts to release its lease.
     *
     * @strict-properties
     * @not-serializable
     */
    final class ModeToken
    {
        private function __construct() {}
    }
 
    /**
     * @strict-properties
     * @not-serializable
     */
    final class Terminal
    {
        private function __construct() {}
 
        public static function fromStdio(): Terminal {}
 
        /**
         * @param resource $input
         * @param resource|null $output
         */
        public static function fromStreams(
            $input,
            $output = null,
        ): Terminal {}
 
        public function getDimensions(): ?Dimensions {}
 
        #[\NoDiscard(message: "as the returned token must stay alive to keep the raw-mode lease active")]
        public function enableRawMode(): ModeToken {}
 
        public function restoreMode(
            ModeToken $mode,
        ): void {}
 
        public function readKey(
            ?\Time\Duration $timeout = null,
            ?\Time\Duration $sequenceTimeout = null,
        ): Key|string|null {}
 
        public function readLine(): ?string {}
 
        public function readSecret(
            ?\Time\Duration $timeout = null,
            ?\Time\Duration $sequenceTimeout = null,
        ): ?string {}
    }
}

Terminal is the native implementation. It has a private constructor and is created through one of its factories. ModeToken is an opaque object representing one raw-mode lease; it cannot be constructed by userland. Neither class can be cloned or serialized. Dimensions is a readonly value object with a public constructor.

Creating a terminal

Terminal::fromStdio() uses the process standard input and output. It resolves the native standard descriptors or handles when an operation runs and uses the available PHP standard-stream buffering where applicable. It does not independently open the controlling terminal.

Terminal::fromStreams() accepts an input stream and an optional output stream:

$terminal = Terminal::fromStreams($input, $output);

Both arguments must be valid PHP stream resources, except that $output may be null. If it is omitted or null, the input stream is used for both directions. The terminal retains references to the supplied resources and uses those streams, including their PHP buffering. Unlike fromStdio(), it does not retarget itself if the process's standard handles subsequently change.

The streams do not have to be terminals. On an ordinary stream, readKey() decodes byte input, readLine() uses the stream layer, and readSecret() does not write the input to the output stream. enableRawMode() returns a no-op lease: it does not change the stream's blocking mode or turn the stream into a terminal. getDimensions() returns null if native dimensions cannot be obtained. I/O failures still throw TerminalException.

This also allows scripts and tests to supply input without a native terminal. Ordinary streams do not simulate terminal dimensions, resize events, or native mode failures.

Terminal dimensions

getDimensions() queries the output side and returns a Dimensions object. It returns null if no usable native dimensions are available, including when the reported row or column count is zero. It does not fall back to the COLUMNS or LINES environment variables.

Applications can also construct dimensions themselves:

$dimensions = new Io\Terminal\Dimensions(80, 24);

Both dimensions must be greater than zero; otherwise the constructor throws ValueError.

Raw mode

A terminal normally buffers input until Enter is pressed, echoes typed characters, and handles some control characters itself. Raw mode lets an application receive input as it arrives and decide what to do with it. A menu that responds to arrow keys is one example.

On a native terminal or console, raw mode has the following effects:

  • Input is available without waiting for Enter, and typed input is not automatically echoed.
  • The terminal's usual line buffering and editing are disabled.
  • Ctrl+C and Ctrl+D are available as input instead of being consumed by the terminal's usual signal or end-of-input processing. Signals delivered independently of terminal input are unaffected.
  • Output post-processing is not changed. On POSIX, the existing output settings are preserved whether output post-processing was enabled or disabled. On Windows, virtual terminal input and output settings are left unchanged.

readKey() and readSecret() manage their own temporary terminal mode. An application that needs raw mode across several operations can keep a lease:

$mode = $terminal->enableRawMode();
 
try {
    // Read keys and redraw the interface.
} finally {
    $terminal->restoreMode($mode);
}

Each call to enableRawMode() returns a separate ModeToken. Keep the token for as long as the lease is needed: Terminal does not retain it. The method is marked #[\NoDiscard] so that accidentally discarding the result emits a warning. An explicit (void) cast suppresses the warning, but the discarded token still does not keep a lease active.

Leases are shared per logical terminal within a PHP request. When the first lease is acquired, Terminal reads and saves the terminal's current mode attributes before switching to raw mode:

  • On POSIX, this is the termios structure for the terminal descriptor: input flags, output flags, control flags, local flags (such as whether typed characters are echoed, whether input is buffered by line, and whether Ctrl+C or Ctrl+Z generate signals), and the control-character array (c_cc, including the VMIN and VTIME read parameters).
  • On Windows, this is the console input mode flags returned by GetConsoleMode() (such as line buffering, echo, Ctrl+C processing, and window-resize input records).

The terminal's dimensions (columns and rows), cursor position, and screen contents are separate from these mode attributes; resizing the window while raw mode is active is not reverted when the mode is restored.

Later leases on the same terminal share that initial snapshot; releasing an intermediate lease leaves raw mode active, and the saved attributes are restored when the last lease is released. Unrelated terminals, including unrelated pseudo-terminals, have separate lease state. Leases can be released in any order:

<?php
 
use Io\Terminal\Terminal;
 
$terminal = Terminal::fromStdio();
$first = $terminal->enableRawMode();  // Saves the settings and enters raw mode.
$second = $terminal->enableRawMode(); // Two leases are active.
$third = $terminal->enableRawMode();  // Three leases are active.
 
unset($second);                 // Releases one lease; raw mode remains active.
$terminal->restoreMode($first); // One lease remains.
$terminal->restoreMode($third); // The final release restores the saved settings.

A token can outlive the Terminal object that created it. Another wrapper for the same logical terminal can release it:

<?php
 
use Io\Terminal\Terminal;
 
$terminal = Terminal::fromStdio();
$lease = $terminal->enableRawMode();
unset($terminal); // The lease is still active.
 
$terminal = Terminal::fromStdio(); // Starts in raw mode, because the mode lease is active.
$terminal->restoreMode($lease);

Restoration uses an independent native descriptor or handle. Closing the original PHP stream therefore does not by itself prevent restoration.

restoreMode() requires a token and returns void. A consumed, invalid, or unrelated token causes ValueError. Failure to acquire a native lease or change the mode throws TerminalException. If explicit restoration of the final lease fails, it also throws TerminalException and leaves the token active, so the caller can retry.

Destroying the last reference to an active token attempts to release its lease. Request shutdown also attempts to restore active modes. These attempts are best-effort; use restoreMode() when the application needs to receive a restoration error. Abrupt process termination may leave the terminal mode unrestored.

A token belongs to the process that acquired it. After pcntl_fork(), destruction of an inherited token or shutdown in the child does not release the parent's lease. Explicit restoration of an inherited parent token in the child throws ValueError.

On an ordinary stream, the no-op token follows the same ownership, lifetime, and consumed-token rules. It is associated with the input stream and can be released through another Terminal wrapping that same stream. It does not prevent readLine() on the ordinary stream.

Leases do not give PHP exclusive access to a terminal. Another process can change its settings while a lease is active. A later acquisition may reapply raw mode, but it does not replace the original snapshot. The final release restores that snapshot rather than merging external changes. This also applies if the terminal was already raw when the first lease was acquired: the saved raw settings are restored on final release.

Reading keys

readKey() returns a Key case for a recognized special key, a string for other input, or null when no input result is available before the timeout. EOF and terminal, input, or polling failures throw TerminalException (on a terminal in raw mode, pressing Ctrl+D delivers the byte “\x04” rather than EOF).

readKey() is meant for scripts and simple interactive tools. It does not report modifier state, mouse input, pasted text as a unit, or focus changes, and it does not write anything to the terminal to enable such reporting. On POSIX terminals and byte streams, a complete escape sequence that does not map to a Key case is returned unchanged as a string; for example, Ctrl+Left in many terminals returns “\x1b[1;5D”. Applications can map such sequences themselves, and libraries with their own input decoder can hold a raw-mode lease and read the input stream directly instead of calling readKey(). A richer input API could be proposed separately and added next to readKey().

A resize is reported as Key::Resize; the caller can then use getDimensions() to obtain the current dimensions. On POSIX, several changes can coalesce into one notification. Calling getDimensions() does not acknowledge a pending resize.

The overall $timeout has four cases:

  • null: wait without a finite deadline.
  • Zero: make a non-blocking attempt.
  • A positive duration: wait up to that duration.
  • A negative duration: throw ValueError.

On POSIX, and on ordinary byte streams on either platform, keys such as arrows can arrive as escape sequences. $sequenceTimeout controls how long to wait for more bytes after an Escape, so that the method can distinguish the Escape key from the start of a sequence. The default for a blocking read is 25 milliseconds. A negative duration throws ValueError.

A zero sequence timeout disables the extra wait, as does an overall timeout of zero. Either still permits a complete sequence to be decoded when its bytes are already available. If there is an overall deadline, the sequence wait is capped at the time remaining; a longer sequence timeout is valid and does not throw.

If no continuation arrives within the window, Key::Escape is returned. If part of a sequence has already been consumed, its prefix may instead be returned as a string. For example, an incomplete ESC [ can return:

"\x1b["

A byte arriving after that is read independently by the next call. Escape-sequence handling can therefore return a key or a consumed prefix rather than null when a timeout is reached.

UTF-8 continuation bytes use the overall timeout, not $sequenceTimeout. If that timeout expires partway through a multibyte value, the bytes are retained for a later readKey() call. Incomplete UTF-8 at EOF throws TerminalException.

Native Windows consoles use console input records for key decoding. $sequenceTimeout is validated there but is not used for that decoding. Ordinary Windows byte streams use the escape-sequence decoder and its sequence timeout.

Reading lines

readLine() reads a line and removes a trailing LF or CRLF. It preserves spaces, tabs, and other data:

"hello\n"   -> "hello"
"hello\r\n" -> "hello"
"\n"        -> ""
"\r\n"      -> ""

Immediate EOF returns null. If EOF follows data without a newline, the final unterminated line is returned. A bare CR at EOF in a byte stream remains part of that line.

PHP already provides fgets() and other line-reading functions. readLine() makes line input available on the same object as key and secret input, handles native Windows console line input, and checks for a conflicting managed raw-mode lease. It returns the submitted value without the Enter delimiter, like readSecret(); fgets(), by contrast, preserves the line ending.

  • POSIX terminals use their existing line discipline. readLine() does not put them into raw mode.
  • Windows consoles use native line input, with the previous console mode restored after the read.
  • Ordinary PHP streams use the stream layer and retain its buffering, blocking mode, and read-timeout behavior. Use a blocking stream when a complete line is required.

For native POSIX terminal reads, EAGAIN and EWOULDBLOCK cause the method to wait for readability and continue until a newline or EOF. It does not change descriptor flags or treat temporary unavailability as EOF. On a Linux PTY, closure reported as EIO is handled as EOF; this does not change error handling for arbitrary non-terminal streams.

An active managed raw-mode lease on the same native terminal prevents readLine(), even if it was acquired through another wrapper. The method throws TerminalException rather than suspending or releasing the lease. A no-op lease on an ordinary stream does not prevent line reading. Terminal does not provide a separate boolean raw-mode getter: at the OS level, terminal mode is a collection of independent flags rather than a single boolean state, and within PHP raw-mode ownership is represented directly by the ModeToken lease.

On byte streams, incomplete UTF-8 bytes retained by the same Terminal from an earlier key read are prepended to the line. Line-ending removal applies to the complete assembled line.

There is no timeout argument on readLine(), because it delegates directly to the OS terminal or console's native line-input mode. Applications and libraries that want custom line or multiline editing, history, tab completion, or syntax highlighting can build those in userland on top of enableRawMode(), readKey(), and getDimensions(), or use PHP's optional readline extension.

Reading secrets

readSecret() reads a value without echoing it. It manages the temporary terminal mode itself, so the caller does not need to acquire a raw-mode lease first. On an ordinary stream there is no native echo mode to change, and the method does not write the input to the output stream.

Enter submits the value. On byte streams, CR or LF submits it, and CRLF is treated as one delimiter even if the bytes arrive separately. A later read through the same Terminal does not receive the LF from that delimiter as a separate key or empty line. Input after the delimiter remains available.

Backspace removes the previous UTF-8 code point for well-formed UTF-8 input. Both BS (0x08) and DEL (0x7F) have this effect on byte streams; backspace on an empty value has no effect. This is code-point editing, not grapheme-cluster editing or normalization. Windows console text is converted to UTF-8; arbitrary byte-stream input is not guaranteed to be valid UTF-8.

Standalone Escape, Ctrl+C, and Ctrl+D cancel the read with TerminalException. Ctrl+D does not submit a partial value. Navigation and function keys are consumed without being added to the secret. There is no cursor navigation, history, completion, prompt rendering, or masking output.

$timeout follows the same rules as readKey(): null waits without a finite deadline, zero makes a non-blocking attempt, a positive duration sets an overall deadline, and a negative duration throws ValueError. Zero allows already-available input to be processed without waiting for more. A positive deadline covers both waiting and input processing; additional input or escape-sequence bytes do not restart it. Scheduling and cleanup can add overhead to the requested duration.

A submitted value is returned as a string, including “” for an empty value. A timeout before submission returns null. EOF, cancellation, and operational failures throw TerminalException. An unsubmitted value is discarded on timeout, cancellation, or failure, and already-consumed input is not rewound.

$sequenceTimeout controls how long to wait for continuation bytes after an Escape before treating it as a standalone key and cancelling the read. Like readKey(), it defaults to 25 milliseconds for blocking reads, is disabled when zero or when the overall timeout is zero, and is capped at the remaining overall time. A negative duration throws ValueError. On native Windows consoles, $sequenceTimeout is validated but is not used for escape decoding because console input records are used.

Before returning or throwing, the method attempts to restore the native mode that was in effect before the read. An existing raw-mode lease remains active. A restoration failure throws TerminalException, even if a value was submitted or the read would otherwise have returned null.

Input state and sequential reads

While raw-mode leases are shared per physical terminal, input decoding state belongs to each individual Terminal instance. That per-instance state consists of:

  • Incomplete UTF-8 byte sequences when readKey() times out mid-character.
  • Split CRLF tracking when readSecret() stops at CR (\r) on an unbuffered byte stream without reading ahead to wait for LF (\n).
  • Pending Windows console input records (such as multi-count key events or UTF-16 surrogate pairs).

When switching between readKey(), readSecret(), and readLine() on the same input, reuse the same Terminal instance so that each read sees the decoder state left by the previous one:

<?php
 
use Io\Terminal\Terminal;
 
$input = fopen('php://memory', 'w+');
fwrite($input, "\x1b[Aexample\r\nWidget\r\n");
rewind($input);
 
$terminal = Terminal::fromStreams($input);
$key = $terminal->readKey();       // Key::Up (consumes "\x1b[A")
$secret = $terminal->readSecret(); // "example" (stops at "\r" and records that a paired "\n" may follow)
$label = $terminal->readLine();    // "Widget" (skips the paired "\n" from the secret's "\r\n", then reads the line)

On an unbuffered byte stream, readSecret() reads one byte at a time so that a standalone \r submits immediately instead of blocking for another byte. When the input uses \r\n, the \n byte may therefore still be sitting in the stream when readSecret() returns. Keeping the same Terminal instance lets the next readKey(), readSecret(), or readLine() call skip that single trailing \n. Likewise, if readKey() times out partway through a multibyte UTF-8 character, the bytes already read are kept in that Terminal instance and used by its next byte-stream read.

If two distinct Terminal instances read from the same underlying stream, they share the stream cursor but do not share decoder state:

<?php
 
use Io\Terminal\Terminal;
 
$input = fopen('php://memory', 'w+');
fwrite($input, "secret\r\nWidget\r\n");
rewind($input);
 
$first = Terminal::fromStreams($input);
$second = Terminal::fromStreams($input);
 
$secret = $first->readSecret(); // "secret" (reads "secret\r"; $first records that a trailing "\n" may follow)
$empty = $second->readLine();   // "" ($second does not share $first's CRLF state, so it reads the leftover "\n" as an empty line)
$label = $second->readLine();   // "Widget" (reads the next line from the shared stream)

The same applies if a partial UTF-8 character times out during $first->readKey(): the leading byte remains in $first's buffer, so a subsequent read on $second sees only the remaining continuation bytes from the stream. The API does not add a reader lock or coordinate reads across separate Terminal instances.

Error model

The methods use null for different kinds of absence:

Method Meaning of null
getDimensions() No usable native dimensions are available.
readKey() No input result is available before the timeout.
readLine() EOF was reached before any line data.
readSecret() The read timed out before submission.

restoreMode() returns void after a successful lease release. Operational failures throw TerminalException. EOF during readKey(), and EOF or cancellation during readSecret(), also use that exception.

readKey() throws TerminalException on EOF rather than returning a Key case like Key::Resize because the two conditions behave differently in a key-reading loop:

  • On an interactive terminal in raw mode, pressing Ctrl+D sends the byte “\x04” (which readKey() returns as “\x04”), not an OS-level EOF. Actual EOF only occurs when the underlying stream, pipe, or terminal descriptor has closed.
  • After Key::Resize, the terminal remains open and subsequent readKey() calls wait for the next key as usual. After EOF, the input is closed and every subsequent readKey() call hits EOF immediately; returning a Key case would cause a typical readKey() loop that ignores unhandled keys to spin indefinitely on a closed stream.

This RFC does not add separate exception subclasses or reason codes for those cases; exception messages are diagnostic text, not stable reason identifiers.

Invalid argument values, such as negative durations, non-positive dimensions, or consumed tokens, throw ValueError. PHP's usual type and argument-count checks apply, including when the required restoreMode() token is omitted.

Backward incompatible changes

None.

Proposed PHP version

PHP 8.7.

RFC impact

To the ecosystem

Libraries can use the native implementation where it is available and retain fallbacks for older PHP versions. Scripted streams can be used to test key, line, and secret input:

$input = fopen('php://temp', 'w+');
fwrite($input, "Widget\nsecret\n");
rewind($input);
 
$terminal = Terminal::fromStreams($input);
 
assert($terminal->readLine() === 'Widget');
assert($terminal->readSecret() === 'secret');

This does not simulate every terminal operation. Dimensions, resize events, and native mode failures still need native tests or an application-defined abstraction. An application that needs a replaceable contract for those operations can define one in userland.

Full-screen programs and editors can be built on top of this API in two ways.

The first uses readKey(). While a ModeToken lease is held, the program reads keys, keeps its own text buffer and cursor position, draws with escape sequences written to the output stream, and calls getDimensions() again after Key::Resize. readKey() recognizes arrows, Home, End, Page Up, Page Down, Insert, Delete, Backspace, Tab, Shift+Tab, Enter, Escape, and F1 to F12. Typed text is returned as UTF-8 strings, and control keys arrive as their control bytes, for example “\x01” for Ctrl+A. Escape sequences that are not in the Key enum, such as “\x1b[1;5D” for Ctrl+Left, are returned unchanged as strings, so a program can map additional sequences itself. This is enough for a line editor with history and completion, or a simple multiline editor.

The second is for libraries that already have their own input decoder, for example to handle modifiers, mouse reporting, bracketed paste, or the kitty keyboard protocol. These libraries hold a ModeToken lease and getDimensions() from this API, and continue to read bytes from the input stream with their own decoder. This is how the phasync/tui port mentioned above works. A future RFC could add a richer input decoder to core; readKey() does not prevent that.

To existing extensions

The implementation is in ext/standard. No existing extension API is removed or changed. The optional readline extension is unaffected. The separate ext-terminal extension can continue to be used on older PHP versions and to explore features outside this RFC.

To SAPIs

The main use case is CLI. The classes and enum are also available in other SAPIs; each operation follows the behavior described above when no terminal is attached. readLine() supports redirected PHP streams.

Alternatives considered

Existing streams and readline

Streams already cover ordinary line input. They do not by themselves provide the proposed cross-platform raw-mode ownership, terminal sizing, and native key and secret reads. The optional readline extension provides a separate line-input API; this RFC does not change or replace it.

Higher-level UI and editor widgets in core

The reference extension includes higher-level prompt and line-editor helpers, and earlier drafts considered bundling more of them in core. This RFC instead focuses on the foundational terminal primitives (mode leases, dimensions, and key, line, and secret reads) so that userland libraries can build their own editors, prompts, and TUI frameworks on top without PHP prescribing a single rendering or widget model.

Userland interfaces

Earlier drafts proposed interfaces for the terminal and mode token. Version 0.4 instead uses final native classes and accepts ordinary streams for scripted input. Applications that need to replace operations which streams cannot simulate can define their own interfaces. Separate stdio and supplied-stream implementation classes, procedural duplicates, and separate width and height getters are also not proposed.

Discussion status

The RFC remains under discussion. Version 0.4 replaced the earlier interfaces and native implementation classes with final Terminal and ModeToken classes, required an explicit token for restoreMode(), added ordinary-stream support and no-op leases, and added Key::Insert and Key::ShiftTab.

Version 0.5 added the NoDiscard warning, examples for lease ownership and sequential reads, and clarifications to the saved mode, escape-sequence timeout, resize notifications, and line endings.

Version 0.6 renames TerminalSize and getSize() to Dimensions and getDimensions(), clarifies the saved terminal attributes and readKey() EOF behavior, and adds a multi-instance input example.

The discussion has also raised questions about the scope of the read methods, richer input events, Windows virtual terminal settings, and the presentation of token destruction. These remain open for discussion; listing features as future scope is not a commitment to a particular later design.

Future scope

The following are outside this RFC. Some are available or have been explored in the reference extension:

  • Lower-level input events, including modifiers and key releases.
  • ANSI support and color-depth detection.
  • Setting the terminal title and ringing the terminal bell.
  • Terminal-size fallbacks using environment variables.
  • Prompt rendering, history, completion, and configurable key bindings.
  • Multiline or rich line editing, syntax highlighting, and timed or higher-level editable line input.

These may be proposed separately.

Voting choices

Primary vote requiring a 2/3 majority to accept the RFC:

Vote: Implement Io\Terminal for PHP 8.7 as outlined in the RFC? — Yes: 0 · No: 0 · Abstain: 0 (closed)

Acceptance requires at least two-thirds of the Yes and No votes to be Yes. Abstentions are excluded from that calculation. There are no secondary votes.

Voting is not open. The opening and closing dates will be announced on internals when voting starts, after the required cooldown and an Intent to Vote notice.

Patches and tests

Implementation PR: https://github.com/php/php-src/pull/23941

Reference extension: https://github.com/prateekbhujel/php-terminal

The implementation includes PHPTs for creation, sizing, scripted-stream input, raw-mode leases, key decoding, timeouts, resize handling, UTF-8 fragments, line input, buffered and redirected streams, and secret input.

POSIX PTY tests cover multiple wrappers for one terminal, unrelated terminals, out-of-order lease release, cross-wrapper restoration, token lifetime, EOF, restoration after closing the original stream, and line reads from nonblocking terminal descriptors. Additional tests cover output-mode preservation, fork ownership, and acquisition and restoration failures.

Input-transition tests cover retained UTF-8 bytes and CRLF handling across key, line, and secret reads, including split delimiters and preservation of line data. Timeout tests cover nonblocking reads and overall deadlines during input and escape-sequence processing.

Separate from the PR's PHPTs and official CI, a Windows console harness injects native input records to exercise key decoding, Unicode, repeat counts, secret input, line input, and mode restoration. Ordinary-stream tests exercise the byte-stream path and do not replace native console checks.

Current build and test results are available in the implementation PR.

Implementation

The implementation is in ext/standard, alongside the existing Io code:

https://github.com/php/php-src/pull/23941

POSIX uses native terminal APIs and PHP's polling support. Windows uses the Console API.

References

Previous discussion:

Related work:

Rejected features

Earlier drafts considered a larger API. The following were left out:

  • Procedural functions duplicating the object methods.
  • Separate stdin, stdout, and stderr terminal objects.
  • Separate native classes for stdio and supplied streams.
  • A public Terminal constructor alongside the factories.
  • Separate getWidth() and getHeight() methods.
  • A complete portable line editor.
  • Compatibility-only APIs from older ext-terminal releases.
  • The complete ext-terminal 1.x API.

Changelog

  • 2026-11-09: Version 0.6. Rename TerminalSize and getSize() to Dimensions and getDimensions(), clarify the saved terminal attributes and readKey() EOF behavior, add $sequenceTimeout to readSecret(), simplify backward compatibility to None, document what readKey() does not cover and how libraries with their own input decoder use the API, and expand the lease and multi-instance examples.
  • 2026-11-06: Version 0.5. Mark enableRawMode() as NoDiscard, add lease and sequential-read examples, and clarify the saved mode, escape-sequence timeout, resize notifications, and line endings.
  • 2026-10-09: Add the closed primary voting widget with Yes, No, and Abstain options. The proposed API is unchanged.
  • 2026-10-06: Version 0.4. Use final native Terminal and ModeToken classes, support scripted ordinary streams and no-op mode leases, require explicit-token restoreMode(): void, remove retained latest-token behavior, add Insert and ShiftTab, and clarify mode lifetime, input state, factory binding, and validation status.
  • 2026-09-30: Version 0.3. Rename the public contracts to Terminal and ModeToken, rename the native implementations to SystemTerminal and SystemModeToken, add readLine(): ?string, and clarify token retention, EOF, argument errors, and POSIX partial-input behavior.
  • 2026-09-29: Add replaceable terminal and mode-token contracts, use null for absence/timeouts, add a timeout to readSecret(), and expand the raw-mode documentation.
  • 2026-09-28: Address discussion feedback on API naming, TerminalSize construction, error and timeout semantics, and shared raw-mode ownership.
  • 2026-09-28: Clarify scope, implementation status, test coverage, and open review questions.
  • 2026-09-27: Initial draft.