PHP CLI getting input from user and then dumping into variable possible?

PHP CLI getting input from user and then dumping into variable possible?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Interactive Input in PHP CLI

Yes, you can absolutely get input from a user in a PHP CLI script and store it in a variable, just like you would with C++'s cin. The mechanism relies on reading from the standard input stream (STDIN). Unlike web development where data arrives over HTTP, CLI scripts interact directly with the shell or terminal session.

The most straightforward way to handle this is using the built-in readline() function. This function attempts to read a line of text from the standard input buffer and store it in a variable. If no data is available, it blocks until input is provided. Here is how you can implement a basic interactive prompt:

<?php

echo "Please enter your name: ";
$name = readline();

if ($name !== false) {
    echo "Hello, $name!";
} else {
    echo "No input received.";
}
?>

When you run this script, the terminal cursor will appear after the prompt. You can type text and press Enter. The readline() function captures that string into $name. It returns false only if an end-of-file condition is reached or if reading fails due to an error.

Handling Control Characters and History

One of the distinct advantages of using readline() over the lower-level fopen('php://stdin', 'r') approach is its built-in support for keyboard interrupts and history management. When a user presses Ctrl+C, readline() allows you to catch the signal gracefully or handle it via the $SIGINT variable, whereas raw file reading might just terminate abruptly depending on how the stream is configured.

Additionally, readline() respects the shell's readline history if it is available. If a user starts typing and then decides to press Ctrl+P (or Up Arrow), they can cycle through previous commands entered in that session. This behavior is inherited from the GNU Readline library and makes CLI tools feel much more polished without needing external dependencies.

Alternative Approaches with Pure PHP Streams

If you cannot use readline()—perhaps because the environment is restricted or you need to read multiple lines without blocking on a single newline—you can open the standard input as a stream resource. However, this approach requires careful handling of the buffering. By default, PHP buffers streams. To get immediate input, you must set the buffer size to 0:

<?php

$handle = fopen('php://stdin', 'r');
if ($handle !== false) {
    stream_set_blocking($handle, true);
    stream_set_buffer_size($handle, -1); // Unbuffered read
    
    echo "Enter text (Ctrl+D to finish): ";
    $line = fgets($handle);
    
    if ($line !== false) {
        $input = trim($line);
        echo "You said: $input";
    }
} else {
    echo "Failed to open stdin.";
}
?>

Note that fgets() reads until a newline character or EOF is encountered. This is functionally similar to readline() but lacks the interactive history and tab-completion features. You must manually manage the file pointer and ensure the stream is not blocking indefinitely if you expect multiple inputs.

Leveraging External Tools with PHP

The original question also asked about using Linux commands. You can invoke external utilities like fzf or rlwrap to enhance input capabilities, but doing so usually requires wrapping them in a shell script first and then passing the output back to PHP via stdin/stdout redirection.

# Example: Using rlwrap to add history to a simple PHP script
php script.php | rlwrap

In this setup, rlwrap intercepts the terminal input before it reaches PHP, providing history navigation and search capabilities. The data still flows through STDIN, but the processing is offloaded to the C library layer. This is useful if you want to build a CLI tool that feels like a mature application without writing complex logic in PHP itself.

Trade-offs and Pitfalls

When designing interactive CLI tools, consider where your script will run. If it is executed by a cron job or a non-interactive shell (like nohup), attempting to read from STDIN will likely block execution indefinitely because no data is being piped in. Always check if the script is running interactively before prompting for input, or provide a default value to prevent hanging processes.

Using readline() is generally preferred for modern PHP CLI applications due to its ease of use and built-in robustness. However, it requires the underlying system to have the Readline library installed. If you are deploying to a minimal container environment where that library is missing, falling back to fgets on a raw stream is your only option.

For developers working within the Laravel ecosystem, similar patterns exist for artisan commands, though they often rely on the Symfony Console component's built-in input handling rather than direct PHP CLI functions.

Our network