PHP 5.4.37 Released

Shell Interativo

A partir do PHP 5.1.0, o CLI SAPI fornece um shell interativo usando a opção -a se o PHP for compilado com a opção --with-readline .

Usando o shell interativo você será capaz de escrever código PHP e executa-lo diretamente.

Exemplo #1 Executando código usando o shell interativo

$ 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 >

O shel interativo também possui sugestões de complemento com tab para funções, constantes, nomes de classes, variáveis, chamadas para métodos estátivos e constantes de classe.

Exemplo #2 Sugestões de complemento com tab

Pressionar a tecla tab duas vezes quando tiver mais de uma sugestão de complemento resultará numa lista desses complementos.

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

Quando existir apneas um possível complemento, pressionar a tecla tab uma vez irá completar o restante da mesma linha:

php > strpt[TAB]ime(

Complementos também funcionarão para nomes que forem definidos durante a mesma sessão do shell interativo:

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

O shell interativo armazena seu históricos que pode ser acessado usando as teclas para cima e para baixo. O histórico é salvo no arquivo ~/.php_history.

A partir do PHP 5.4.0, o CLI SAPI fornece as configurações do php.ini cli.pager e cli.prompt. A configuração cli.pager permite que um programa externo (como o less) aja como uma alternativa para a saida ao inves dela ser exibida diretamente na tela A configuração cli.prompt az com que seja possível alterar a saída php >.

No PHP 5.4.0 também é possível definir configurações php.ini no shell interativo usando uma notação abreviada.

Exemplo #3 Definindo configurações php.ini no shell interativo

A opção cli.prompt:

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

Usando crase é possível executaro PHP diretamente no terminal:

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 >

Setando o paginador paraless:

php > #cli.pager=less
php > phpinfo();
(output displayed in less)
php >

A configuração cli.prompt suporta algumas sequencias de escape:

Sequencias de escape do cli.prompt
Sequencia Descrição
\e Usada para adicionar cores ao terminal. Um exemplo pode ser \e[032m\v \e[031m\b \e[34m\> \e[0m
\v A versão do PHP.
\b Indica em qual bloco o PHP está. Por exemplo /* irá indicar que o PHP está dentro de um comentário de mltiplas linhas. O escopo externo será denominado por php.
\> Indica o caracter do terminal. Por padrão é >, mas pode alterar qaundo o shell estiver dentro de um bloco indeterminado ou de uma string. Possíveis caracteres são: ' " { ( >

Nota:

Arquivos incluídos atraves de auto_prepend_file e auto_append_file são interpretados nesse modo porem com algumas restrições - Exemplo: funções devem ser definidas antes de sua chamada.

Nota:

Autoloading não está disponível quando estiver usando o PHP no modo interativo da CLI.

add a note add a note

User Contributed Notes 9 notes

up
42
Ryan P
2 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
16
spencer at aninternetpresence dot net
3 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
9
Anonymous
4 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
5
Anonymous
4 years ago
It seems the interactive shell cannot be made to work in WIN environments at the moment. 

Using "php://stdin", it shouldn't be too difficult to roll your own.  You can partially mimic the shell by calling this simple script (Note: Window's cmd already has an input history calling feature using the up/down keys, and that functionality will still be available during execution here):

<?php

$fp
= fopen("php://stdin", "r");
$in = '';
while(
$in != "quit") {
    echo
"php> ";
   
$in=trim(fgets($fp));
    eval (
$in);
    echo
"\n";
    }
   
?>

Replace 'eval' with code to parse the input string, validate it using is_callable and other variable handling functions, catch fatal errors before they happen, allow line-by-line function defining, etc.  Though Readline is not available in Windows, for more tips and examples for workarounds, see http://www.php.net/manual/en/ref.readline.php
up
1
Shane Harter
1 year ago
If you've ever wanted to build your own interactive shell, I released a project recently that makes it insanely easy to build awesome shell apps in PHP. It blends features from Zend2 and Symonfy2 with things like regex routing, state management, etc. Check it out here:

https://github.com/shaneharter/sheldon
up
1
alexandrebr at gmail dot com
3 years ago
For those who (just like me) can't get it working, try to press CTRL+D after inserting some commands.

Example:
php
<?php
echo "Hello World!\r\n";
(
Hit CTRL+D here)
Hello World!

This is NOT interactive mode, but may help you.

To have the "-i" available, you'll need the following arguments while compiling PHP:
--with-readline e --with-libedit
up
0
elijah at elijahlynn dot net
3 months ago
Bug #55496 Interactive mode doesn't force a newline before the prompt => https://bugs.php.net/bug.php?id=55496

Fixed on July 24th, 2014 @ http://git.php.net/?p=php-src.git;a=commit;h=71d3a69425449972f4efdf7228c6f7e49e090755

Until then, this will work:

php -dcli.prompt="\nphp> " -a
up
1
lee8oi at gmail dot com
2 years ago
I use git-bash in windows to connect to my servers via SSH. When I use the interactive mode via 'php -a' command I have to hit ctrl+d twice to execute the entered code. Example:
(<ctrl+d> denotes hitting ctrl & D)

-bash$ php -a
Interactive mode enabled
<?php
echo 'hello world';
?><br />
<ctrl+d>
<ctrl+d>
hello world<br />
-bash$

Note: this still displays the <br /> tag but without the tag your output would likely be attached to your bash prompt like this:

hello world-bash$
up
0
xEviL
4 years ago
When building php on FreeBSD from ports one can add --with-readline option by manually editing the var CONFIGURE_ARGS in Makefile inside the php port directory and proceeding with build as usual.
To Top