Skip to content
#externals
← All RFCs
Discussion

Io\Terminal

by Pratik Bhujel

v0.7 · created 2026-09-27 · targets PHP 8.7

wiki.php.net/rfc/io_terminal ↗

implementation
Contents
  1. Introduction
  2. Motivation
  3. Proposal
  4. Creating a terminal
  5. Terminal dimensions
  6. Raw mode
  7. Reading keys
  8. Reading lines
  9. Reading secrets
  10. Input state and sequential reads
  11. Error model
  12. Backward incompatible changes
  13. Proposed PHP version
  14. RFC impact
  15. To the ecosystem
  16. To existing extensions
  17. To SAPIs
  18. Alternatives considered
  19. Discussion status
  20. Future scope
  21. Voting choices
  22. Patches and tests
  23. Implementation
  24. References
  25. Rejected features
  26. Changelog

Introduction

A PHP command-line program can already read a line from standard input. Reading one arrow key without waiting for Enter, asking for a password without displaying it, or finding out how wide the terminal is takes different code on POSIX and Windows.

This RFC adds Io\Terminal to ext/standard. A program can ask for terminal dimensions, acquire and release raw mode, and read a key, a line or a secret. Programs can also supply ordinary PHP streams when they want to script the input.

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

Motivation

Laravel Prompts uses stty to save and change terminal settings. Symfony Console can use stty on POSIX and mode CON on Windows to determine terminal dimensions. These are reasonable solutions in userland, but they require external commands for information PHP can obtain from the operating system.

There is also an ownership problem. If a menu and a password prompt both need raw mode on the same terminal, finishing one must not restore the terminal while the other still needs it. A lease gives each caller something it can release without having to know who else is using the terminal.

The phasync/tui port illustrates a second use case. Its maintainer tried the proposed API for raw mode and dimensions, kept the library's own input decoder, and reported the same test results as on stock PHP, including its pseudo-terminal restoration tests. He also suggested a smaller API in the discussion. This proposal keeps basic reads for scripts without requiring libraries to adopt PHP's key decoder.

Proposal

The public API is:

<?php
 
namespace Io\Terminal {
 
    /** @strict-properties */
    class TerminalException extends \Io\IoException {}
 
    /** @strict-properties */
    class EofException extends TerminalException {}
 
    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 $columns;
        public readonly int $rows;
 
        public function __construct(int $columns, 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 {}
    }
}

Creating a terminal

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

Terminal::fromStreams($input, $output) binds the supplied PHP stream resources and retains references to them. If output is omitted or null, the input stream is used for both directions. Reopening the process's standard handles does not retarget an object created from supplied streams. Neither factory requires both sides to be native terminals.

On an ordinary input stream, key, line and secret reads use the stream. Raw mode is a no-op: it does not change the stream's blocking mode. A memory stream can supply scripted input but cannot generate a native resize notification or reproduce a failure to change console mode.

Terminal dimensions

getDimensions() queries the output side. It returns a Dimensions object with readonly $columns and $rows properties, or null when usable native dimensions are unavailable. A zero row or column count is not a usable size. The method does not guess from COLUMNS or LINES.

Applications may construct a value directly, including with named arguments:

$size = new \Io\Terminal\Dimensions(columns: 80, rows: 24);

Each argument must be greater than zero; otherwise the constructor throws ValueError. Querying the dimensions does not consume a pending resize notification.

Raw mode

In raw mode, input is available without waiting for Enter, typing is not echoed, and the terminal does not perform its usual line editing. Ctrl+C and Ctrl+D are available as input. Signals sent independently of terminal input are unaffected. Output post-processing is left as it was. On Windows, the virtual-terminal input and output flags are also left as they were.

enableRawMode() returns a separate ModeToken for each acquisition. The first lease for a logical terminal in a PHP request saves the current mode. On POSIX this is the terminal's termios state: input, output, control and local flags, and its control characters, including VMIN and VTIME. On Windows it is the input mode returned by GetConsoleMode(). Neither snapshot includes dimensions, cursor position or screen contents. Releasing the last lease will not undo a window resize.

$first = $terminal->enableRawMode();   // Saves the mode and enters raw mode.
$second = $terminal->enableRawMode();  // Another lease on the same terminal.
 
$terminal->restoreMode($first);        // The second lease keeps raw mode active.
$terminal->restoreMode($second);       // Restores the settings saved by the first.

Leases can be released in any order. Different terminals have independent leases. Wrappers for the same native terminal share its leases, and a token may outlive its original wrapper:

$terminal = \Io\Terminal\Terminal::fromStdio();
$mode = $terminal->enableRawMode();
unset($terminal);
 
$again = \Io\Terminal\Terminal::fromStdio(); // The same terminal is still in raw mode.
$again->restoreMode($mode);

Keep the token for as long as the mode is needed. enableRawMode() has the NoDiscard attribute: discarding its result emits a warning. An explicit void cast can silence that warning but does not keep a lease alive. Neither ModeToken nor Terminal can be cloned or serialized.

restoreMode() returns void. An invalid, consumed or unrelated token causes ValueError. If explicit final restoration fails, it throws TerminalException and the token stays active so the caller can retry. Destruction of a token and request shutdown attempt cleanup on a best-effort basis; use explicit restoration when the caller needs to handle failure. Restoration retains its own native descriptor or handle, so closing the original PHP stream does not by itself prevent restoration.

After pcntl_fork(), a child cannot release a lease acquired by its parent. Explicit use of an inherited parent token in the child throws ValueError; destroying the inherited token or shutting down the child does not restore the parent's terminal.

A lease is not an exclusive lock on the device. Another process may change the terminal while a lease is active. A later acquisition may reapply raw mode, but the final release restores the original snapshot, including when the terminal was already raw before PHP acquired it.

On an ordinary stream, a no-op token follows the same lifetime and ownership rules. It belongs to the input stream and can be released through another wrapper for that same stream. It does not prevent line reads.

Why there is no raw-mode getter

PHP can read the current native settings. They answer questions such as whether echo is enabled or whether Ctrl+C produces a signal. Those settings can vary independently: echo can be off while signal processing is still on. They also do not say whether PHP holds a lease. Another program can set the same flags without acquiring one.

The rule for readLine() is about lease ownership: an active PHP lease on the same native terminal prevents the read. Inspecting the native flags would answer a different question. This RFC exposes neither a boolean named isRawMode() nor a lease-state getter.

Reading keys

readKey() returns a Key case for a recognized special key or resize notification, a string for other input, or null when no input result is available before the timeout. It manages any temporary terminal mode it needs. An application does not have to acquire a lease just to read one key.

On a byte stream, printable characters are normally returned as strings, and controls without a named key can be returned as their input bytes. Ctrl+D in native raw mode is the byte 0x04; it is not an end-of-file indication. If input ends before a key can be returned, readKey() throws EofException. That includes EOF partway through a UTF-8 character. Input, polling and terminal-mode failures throw TerminalException.

The overall timeout is a Time\Duration. A null timeout waits without a finite deadline; zero checks what is available without waiting; a positive duration sets a deadline. Negative durations are invalid and throw ValueError.

On POSIX terminals and ordinary byte streams, a single Escape and the start of an arrow-key sequence have the same first byte. $sequenceTimeout controls the extra wait for continuation bytes after Escape; the default window for a blocking read is 25 ms. It starts after the initial Escape arrives. Where there is an overall deadline, the extra wait cannot extend it. A zero sequence timeout or zero overall timeout prohibits waiting but still permits a complete, already available sequence to be decoded.

A lone Escape can produce Key::Escape. If more of a sequence has been consumed but the sequence is incomplete, the consumed prefix can instead be returned as a string; a later byte is then read independently. A timeout between UTF-8 bytes works differently: the decoder retains the partial character for the next read. UTF-8 continuation uses the overall timeout, not the Escape window.

On native Windows consoles, PHP reads console input records. It validates $sequenceTimeout but does not use it to decode native key records. An ordinary Windows byte stream uses the byte decoder and the Escape window.

After Key::Resize, call getDimensions() for the current dimensions. A resize notification means the size should be checked, not that exactly one resize occurred. Several POSIX changes can coalesce. Reading the dimensions first does not acknowledge the notification.

Key cases and compatibility

The enum lists the keys recognized by this proposal. Applications interested in only a few cases should allow for other cases, for example by including a default arm in a match. The enum is not a promise that PHP will never recognize another key.

There are two compatibility questions when extending it. Suppose a byte-stream application handles Ctrl+Left by comparing the result with the string “\x1b[1;5D”. If a later PHP version maps those bytes to a new Key::CtrlLeft case, the string comparison stops matching. The application may also receive an enum case it has never handled. A default arm handles the second issue; it does not preserve the application's existing Ctrl+Left binding. Recognizing a sequence previously returned as a string therefore needs compatibility review. No such remapping is proposed here.

readKey() does not enable mouse, focus, paste or extended keyboard reporting. Libraries that need to interpret the bytes themselves can acquire a raw-mode lease and read directly from their input stream, using their own decoder throughout.

Reading lines

readLine() removes the terminating LF or CRLF and preserves other bytes, including spaces, tabs and a bare CR at EOF. An empty submitted line is the empty string. If input ends after some line data, the final unterminated line is returned. A read at EOF with no remaining data returns null. readLine() does not throw EofException for this condition.

$input = fopen('php://temp', 'w+');
fwrite($input, "first\r\n\nlast");
rewind($input);
 
$t = \Io\Terminal\Terminal::fromStreams($input);
$t->readLine(); // "first"
$t->readLine(); // ""
$t->readLine(); // "last"
$t->readLine(); // null

POSIX terminals use the existing line discipline. On a nonblocking native terminal descriptor, temporary unavailability causes the read to wait for readability, not to signal EOF or change the descriptor flags. On Linux a PTY closure reported as EIO is handled as EOF; this rule does not turn arbitrary stream errors into EOF. Windows consoles use native line input and restore the previous console mode afterward. Ordinary PHP streams retain their buffering, blocking and stream-timeout behavior; use a blocking stream when a complete line is required.

An active PHP raw-mode lease on the same native terminal, including one held through another wrapper, causes readLine() to throw TerminalException. It does not release or suspend someone else's lease. There is no method-level timeout or portable line editor. History, completion and editable prompts remain userland concerns.

Reading secrets

readSecret() reads input without echoing it on a native terminal. On an ordinary stream there is no native echo setting to change; the method does not copy the secret to the output stream. It displays neither a prompt nor masking characters.

Enter submits the value, including an empty string. On byte streams CR and LF each submit; CRLF counts as one delimiter, even if split across reads. Backspace removes the last UTF-8 code point in well-formed input, not a grapheme cluster. Both BS and DEL act as backspace on byte streams. Backspace on an empty buffer does nothing. Native Windows text is converted to UTF-8; the byte-stream path does not guarantee valid UTF-8 for arbitrary input.

Standalone Escape, Ctrl+C and Ctrl+D cancel the prompt and throw TerminalException, not EofException. Navigation and function keys are consumed without being added to the value. If the input stream ends before submission, the method throws EofException. Neither EOF nor cancellation submits a partial secret.

$timeout follows the same rules as for readKey(). A timeout before submission returns null. A positive deadline covers the whole operation, including time spent processing input and escape sequences; each new byte does not restart it. Scheduling and mode restoration can add overhead. Partial input is discarded on timeout, cancellation or failure, and bytes already consumed are not rewound.

On a byte stream $sequenceTimeout controls the wait after Escape, with the same default, zero-timeout behavior and overall deadline cap as readKey(). The native Windows console validates the argument but decodes input records without that wait.

Before returning or throwing, the method attempts to restore the mode in effect before the read. An existing lease stays active. A restoration failure is a terminal error, even if a value was submitted or the read would otherwise have timed out.

Input state and sequential reads

Mode leases are shared per logical terminal. Input state belongs to each Terminal object: an incomplete UTF-8 character, a possible LF after a secret submitted with CR, or pending Windows input such as key repeats or a UTF-16 surrogate pair.

Use the same object when several reads belong to one conversation:

$input = fopen('php://temp', 'w+');
fwrite($input, "\x1b[Aexample\r\nWidget\r\n");
rewind($input);
 
$t = \Io\Terminal\Terminal::fromStreams($input);
$key = $t->readKey();       // Key::Up
$secret = $t->readSecret(); // "example"
$label = $t->readLine();    // "Widget"

On an unbuffered byte stream a secret read can submit at CR without waiting for LF. The next read through the same object knows to skip one paired LF. A different wrapper shares the underlying stream position but has no record of that CR:

// Assume $input is an unbuffered input stream supplying "secret\r\nWidget\r\n".
$first = \Io\Terminal\Terminal::fromStreams($input);
$second = \Io\Terminal\Terminal::fromStreams($input);
$first->readSecret(); // "secret": the first wrapper stopped at CR.
// If LF is still in the stream, the second wrapper sees it as an empty line.
$second->readLine();

The same distinction applies to a partial UTF-8 character retained after a timeout. A later byte-stream read on the same object can use the retained bytes; another wrapper cannot recover them from the shared stream. Direct stream reads are not coordinated with a Terminal decoder.

Error model

Operation Result when no value is available Other outcomes
getDimensions() null if native dimensions are unavailable or unusable A successful query returns Dimensions.
readKey() null when no key result is available before the timeout EOF before a key can be returned throws EofException.
readLine() null at EOF before any line data An empty submitted line is an empty string; a final unterminated line is returned once.
readSecret() null on timeout before submission EOF throws EofException; cancellation throws TerminalException.

EofException extends TerminalException, which extends Io\IoException. A caller can handle end of input without also catching a failed terminal operation:

try {
    $key = $terminal->readKey();
} catch (\Io\Terminal\EofException $e) {
    return; // No more input. Other terminal errors still reach the caller.
}

EOF is not a Key case. A resize leaves an application waiting for the next key. A closed input pipe can report EOF immediately on every subsequent read; a loop that ignored an EOF key could spin. A seekable file or memory stream can also reach its current end without the stream resource being closed.

Operational failures use TerminalException. There is no separate cancellation subclass or public reason code. Exception messages are diagnostic text. Invalid argument values, including negative durations, non-positive dimensions and consumed tokens, throw ValueError. Normal PHP type and argument-count checks apply.

Backward incompatible changes

None.

Proposed PHP version

PHP 8.7.

RFC impact

To the ecosystem

Small tools can use PHP's decoder directly: a menu can switch on arrow keys, redraw after a resize, and handle ordinary text as strings. Rendering still goes through the application's output stream. Libraries with an existing parser can adopt only mode leases and sizing. Applications that need to replace behavior a stream cannot simulate, such as a failed mode restoration, can define their own interfaces.

To existing extensions

The implementation is in ext/standard. It does not change the optional readline extension. The separate reference extension can continue serving older PHP versions and exploring features outside the core proposal.

To SAPIs

CLI is the main use case. The API is also available to other SAPIs. Availability of a native operation depends on the attached streams or handles, not just on the name of the SAPI.

Alternatives considered

Existing PHP streams already handle ordinary line input. They do not manage shared raw-mode ownership or provide one native key and secret input API for POSIX and Windows. The readline extension addresses a different use case and remains available.

Earlier drafts proposed terminal and token interfaces with separate native implementations. The proposal instead uses final native classes and allows ordinary streams for scripted tests. It does not require an application to mock a terminal just to supply two lines of input.

Prompt rendering, widget behavior and portable line editing remain in libraries. A library can use the native operations without giving up its own key bindings, rendering or editor.

Discussion status

Under discussion. Version 0.7 spells out $columns and adds a specific exception for EOF during key and secret input. It also clarifies which raw-mode state PHP can observe and the compatibility implications of recognizing additional keys. Scope, richer input events and Windows virtual-terminal settings have been raised in discussion; they are not additional features of this revision.

Future scope

Possible separate proposals include richer input events with modifiers or releases, mouse input, terminal capability and color-depth detection, terminal title and bell control, environment-based dimension fallbacks, and higher-level line editing or prompts. This RFC makes no commitment to a particular future event API.

Voting choices

Primary vote:

Vote: Implement Io\Terminal for PHP 8.7 as outlined in the RFC? — (closed)

Acceptance requires at least two-thirds of the Yes and No votes to be Yes. Abstentions are excluded. There are no secondary votes. Voting is not open; dates will be announced on internals.

Patches and tests

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

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

The PHPTs cover creation and dimensions, ordinary streams, raw-mode ownership, key decoding, deadlines, resize notifications, lines and secret input. They distinguish an open writer with no available input from a closed writer, check the EOF exception hierarchy, and exercise truncated UTF-8 and cancellation. Sequential-read tests cover split CRLF and retained input across methods.

POSIX pseudo-terminal tests cover independent and shared terminals, out-of-order release, restoration through another wrapper, token destruction, fork ownership, closed descriptors, native mode errors, output-mode preservation and nonblocking line input.

Separate local Windows console tests inject native input records to exercise Unicode, key repeats, key decoding, secret input, native line input and mode restoration. Scripted stream tests cover the byte decoder and cannot substitute for console input records. Current CI results belong to the implementation PR.

Implementation

The native code lives in ext/standard. POSIX uses terminal attributes and PHP's polling support; Windows uses console modes and console input records. Both platforms also provide a path for ordinary PHP streams.

References

Rejected features

Earlier drafts considered duplicate procedural functions, separate stdin/stdout/stderr terminal objects, separate classes for stdio and supplied streams, a public constructor in addition to the factories, separate width and height getters, and a portable line editor. This proposal does not import the full ext-terminal 1.x API or its compatibility-only methods.

Changelog

  • 2026-11-20: Version 0.7. Rename the Dimensions property and constructor parameter from $cols to $columns. Add Io\Terminal\EofException. Clarify raw-mode inspection and compatibility when extending Key.
  • 2026-11-09: Version 0.6. Rename TerminalSize/getSize() to Dimensions/getDimensions(), describe saved terminal attributes and EOF, add the secret sequence timeout, and expand the lease, multi-wrapper and library-decoder examples. Clarify backward compatibility.
  • 2026-11-06: Version 0.5. Add NoDiscard and examples for leases and sequential reads. Clarify restoration, escape timing, resize and line endings.
  • 2026-10-09: Add the closed Yes/No/Abstain voting widget.
  • 2026-10-06: Version 0.4. Adopt final native classes, scripted streams, no-op leases and explicit token restoration. Add Insert and ShiftTab and clarify input state, lifetime and validation.
  • 2026-09-30: Version 0.3. Revise naming, add readLine(), and clarify token retention, error handling and partial input.
  • 2026-09-29: Propose replaceable terminal and token contracts, null on absence or timeout, and a timeout for readSecret().
  • 2026-09-28: Revise naming, size construction, shared mode ownership, timeouts and errors. Clarify scope, tests and open questions.
  • 2026-09-27: Initial draft.