PHP 8.3.21 Released!

Shell Interactivo

El CLI SAPI proporciona un shell interactivo al usar la opción -a si PHP se ha compilado con la opción --with-readline. Desde PHP 7.1.0, el shell interactivo también está disponible en Windows, si la extensión readline está activada.

Al usar el shell interactivo, tiene la posibilidad de escribir código PHP y que se ejecute directamente.

Ejemplo #1 Ejecución de código usando el shell interactivo

$ php -a
Interactive shell

php > echo 5+8;
13
php > function addTwo($n)
php > {
php { return $n + 2;
php { }
php > var_dump(addtwo(2));
int(4)
php >

El shell interactivo también proporciona autocompletado de funciones, constantes, nombres de clases, variables, llamadas a métodos estáticos y constantes de clases utilizando la tecla de tabulación. Desde PHP 8.4.0, la ruta hacia el archivo de historial puede establecerse utilizando la variable de entorno PHP_HISTFILE.

Ejemplo #2 Autocompletado usando la tecla de tabulación

Presionar dos veces la tecla de tabulación cuando hay varias posibles completaciones mostrará una lista de estas completaciones:

php > strp[TAB][TAB]
strpbrk   strpos    strptime
php > strp

Cuando solo hay una posible completación, presionar la tecla de tabulación una vez completará el resto en la misma línea:

php > strpt[TAB]ime(

La completación también funcionará para los nombres que se han definido durante la sesión actual del shell interactivo:

php > $fooThisIsAReallyLongVariableName = 42;
php > $foo[TAB]ThisIsAReallyLongVariableName

El shell interactivo almacena su historial y puede acceder a él utilizando las teclas arriba y abajo. El historial se guarda en el archivo ~/.php_history.

El CLI SAPI proporciona 2 directivas del php.ini: cli.pager y cli.prompt. La directiva cli.pager permite la definición de un programa externo (como less) a utilizar como pager para la salida en lugar de mostrarla directamente en la pantalla. La directiva cli.prompt permite la modificación del prompt php >.

También es posible definir directivas del php.ini en un shell interactivo utilizando notaciones abreviadas.

Ejemplo #3 Definición de directivas del php.ini en un shell interactivo

La definición de la directiva cli.prompt:

php > #cli.prompt=hello world :>
hello world :>

Utilizando comillas invertidas, es posible ejecutar código PHP en el prompt:

php > #cli.prompt=`echo date('H:i:s');` php >
15:49:35 php > echo 'hi';
hi
15:49:43 php > sleep(2);
15:49:45 php >

Definición del pager a less:

php > #cli.pager=less
php > phpinfo();
(salida mostrada con less)
php >

La directiva cli.prompt soporta algunas secuencias de escape:

Secuencias de escape de cli.prompt
Secuencia: Descripción:
\e utilizado para agregar colores al prompt. Ejemplo: \e[032m\v \e[031m\b \e[34m\> \e[0m
\v La versión de PHP.
\b Indica en qué bloque de PHP nos encontramos. Por ejemplo, /* permite indicar que estamos en un comentario multilínea. El ámbito externo se representa por php.
\> Indica el carácter utilizado para el prompt. Por defecto, será >, pero puede cambiarse cuando el shell se encuentra en un bloque indeterminado o en una cadena de caracteres. Los caracteres posibles son: ' " { ( >

Nota:

Los archivos incluidos a través de auto_prepend_file y auto_append_file se analizan en este modo, pero con algunas restricciones; es decir, las funciones deben haber sido definidas antes de la llamada.

Modo interactivo

Si la extensión readline no está disponible, anterior a PHP 8.1.0, invocar el CLI SAPI con la opción -a proporciona el modo interactivo. En este modo, se supone que se da un script PHP completo a través de STDIN, y después de la interrupción con CTRL +D (POSIX) o CTRL +Z seguido de ENTER (Windows), este script será evaluado. Esto es básicamente idéntico a invocar el CLI SAPI sin la opción -a.

A partir de PHP 8.1.0, invocar el CLI SAPI con la opción -a falla si la extensión readline no está disponible.

add a note

User Contributed Notes 7 notes

up
176
Ryan P
13 years ago
Interactive Shell and Interactive Mode are not the same thing, despite the similar names and functionality.

If you type 'php -a' and get a response of 'Interactive Shell' followed by a 'php>' prompt, you have interactive shell available (PHP was compiled with readline support). If instead you get a response of 'Interactive mode enabled', you DO NOT have interactive shell available and this article does not apply to you.

You can also check 'php -m' and see if readline is listed in the output - if not, you don't have interactive shell.

Interactive mode is essentially like running php with stdin as the file input. You just type code, and when you're done (Ctrl-D), php executes whatever you typed as if it were a normal PHP (PHTML) file - hence you start in interactive mode with '<?php' in order to execute code.

Interactive shell evaluates every expression as you complete it (with ; or }), reports errors without terminating execution, and supports standard shell functionality via readline (history, tab completion, etc). It's an enhanced version of interactive mode that is ONLY available if you have the required libraries, and is an actual PHP shell that interprets everything you type as PHP code - using '<?php' will cause a parse error.

Finally, if you're running on Windows, you're probably screwed. From what I'm seeing in other comments here, you don't have readline, and without readline there is no interactive shell.
up
58
spencer at aninternetpresence dot net
13 years ago
In Windows, press Enter after your ending PHP tag and then hit Ctrl-Z to denote the end-of-file:

C:\>php -a
Interactive mode enabled

<?php
echo "Hello, world!";
?>
^Z
Hello, world!

You can use the up and down arrows in interactive mode to recall previous code you ran.
up
14
#linuxmint-es
7 years ago
For use interactive mode enabled on GNU/Linux on distros Debian/Ubuntu/LinuxMint you must install "php*-cli" and "php*-readline" packages from official repository.
Example:
>$sudo aptitude install php5-cli php5-readline

After that you can use interactive mode.
Example:
~ $ php -a
Interactive mode enabled

php >echo "hola mundo!\n";
hola mundo!
php >

I hope somebody help it!
up
15
Anonymous
14 years ago
Just a few more notes to add...

1) Hitting return does literally mean "execute this command". Semicolon to note end of line is still required. Meaning, doing the following will produce a parse error:

php > print "test"
php > print "asdf";

Whereas doing the following is just fine:

php > print "test"
php > ."asdf";

2) Fatal errors may eject you from the shell:

name@local:~$ php -a
php > asdf();

Fatal Error: call to undefined function...
name@local:~$

3) User defined functions are not saved in history from shell session to shell session.

4) Should be obvious, but to quit the shell, just type "quit" at the php prompt.

5) In a sense, the shell interaction can be thought of as linearly following a regular php file, except it's live and dynamic. If you define a function that you've already defined earlier in your current shell, you will receive a fatal "function already defined" error only upon entering that closing bracket. And, although "including" a toolset of custom functions or a couple of script addon php files is rather handy, should you edit those files and wish to "reinclude" it again, you'll cause a fatal "function x already defined" error.
up
3
Gray
5 years ago
When adding colours, don't forget that PHP uses the same 'readline' as Bash does, so it has the same need to wrap all colour codes in special marker characters.

If you simply add raw colour codes to the prompt, you will notice that long lines no longer get wrapped correctly -- Readline no longer knows how wide the prompt is.

To fix this, you need to start each colour code with an '0x01' byte (aka Ctrl-A aka SOH) and end it with the '0x02' byte (aka Ctrl-B aka STX). There are no escapes for these -- you have to literally put the control characters in your php-cli.ini.

For example:

<?php

// cli.prompt = <SOH>\e[1m<STX> PHP! \> <SOH>\e[m<STX>

echo "cli.prompt = \x01\\e[1m\x02 PHP! \x01\\e[m\x02\n";
?>
up
2
John
7 years ago
If you delete your "~/.php_history", you MUST re-create the file manually!

Because after I deleted my history file, "php -a" (interactive mode) never saved any history anymore.

It only started working after I ran "touch ~/.php_history" to create an empty file. From then on, PHP is saving history again!

I thought this was a bit unusual. Normally, applications recreate their history files themselves. But just be aware of the fact that PHP works this way instead, guys and girls! :-)
up
0
turabgarip at gmail dot com
1 year ago
Note that destructors will not be triggered when exiting interactive shell by any method. (Like CTRL + D, CTRL + Z or CTRL + C).

Since the interactive shell is effectively a continuous runtime, the "end of script" condition is never met for a destructor to run. And exiting the interactive shell is not considered end of script but rather the end of interpreter process. And since the process is dead; it can't run the destructor.

Therefore the only way for a destructor to run is that you remove all the references to the corresponding object. Like:

<?php

class A {
public function
__destructor() {
// This will never run after ending PHP interactive shell session.
}
}

$a = new A();

// This is the only way for the destructor to be able to run.
$a = null; // Or;
unset($a);

?>
To Top