Shell Interactif

Le CLI SAPI fournit un shell intéractif lors de l'utilisation de l'option -a si PHP a été compilé avec l'option --with-readline. Depuis PHP 7.1.0 le shell intéractif est également disponible sur Windows, si l'extension readline est activée.

En utilisant le shell interactif, vous avez la possibilité de taper du code PHP et qu'il soit exécuté directement.

Exemple #1 Exécution de code en utilisant le shell interactif

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

Le shell interactif fournit également une autocomplétion des fonctions, des constantes, des noms de classes, des variables, des appels aux méthodes statiques et des constantes de classes en utilisant la touche de tabulation.

Exemple #2 Auto-complétion en utilisant la touche de tabulation

Le fait de presser deux fois la touche de tabulation lorsqu'il y a plusieurs complétions possibles affichera une liste de ces complétions :

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

Lorsqu'il n'y a qu'une seule complétion possible, presser la touche de tabulation une seule fois complétera le reste sur la même ligne :

php > strpt[TAB]ime(

La complétion fonctionnera aussi pour les noms qui ont été définis lors de la session courante du shell interactif :

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

Le shell interactif stocke votre historique et peut y accéder en utilisant les touches haut et bas. L'historique est sauvegardé dans le fichier ~/.php_history.

Le CLI SAPI fournit 2 directives du php.ini : cli.pager et cli.prompt. La directive cli.pager permet la définition d'un programme externe (comme less) à utiliser comme pager pour la sortie au lieu d'afficher directement sur l'écran. La directive cli.prompt autorise la modification du prompte php >.

Il est également possible de définir des directives du php.ini dans un shell interactif en utilisant des notations raccourcies.

Exemple #3 Définition de directives du php.ini dans un shell interactif

La définition de la directive cli.prompt :

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

En utilisant des backticks, il est possible d'exécuter du code PHP dans le prompte :

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 >

Définition du pager à less :

php > #cli.pager=less
php > phpinfo();
(sortie affichée avec less)
php >

La directive cli.prompt supporte quelques séquences d'échappements :

Séquences d'échappements de cli.prompt
Séquence : Description :
\e utilisé pour ajouter des couleurs au prompte. Exemple : \e[032m\v \e[031m\b \e[34m\> \e[0m
\v La version de PHP.
\b Indique dans quel bloc de PHP nous nous trouvons. Par exemple, /* permet d'indiquer que nous sommes dans un commentaire multilignes. Le scope externe est représenté par php.
\> Indique le caractère utilisé pour le prompte. Par défaut, ce sera >, mais peut être modifié lorsque le shell se trouve dans un bloc indéterminé ou dans une chaîne de caractères. Les caractères possibles sont : ' " { ( >

Note:

Les fichiers inclus via auto_prepend_file et auto_append_file sont analysés dans ce mode, mais avec quelques restrictions - i.e. les fonctions doivent avoir été définies avant l'appel.

Interactive mode

Si l'extension readline n'est pas disponible, antérieur à PHP 8.1.0, invoquer le CLI SAPI avec l'option -a fournit le mode intéractif. Dans ce mode, un script PHP complet est supposé d'être donnée via STDIN, et après l'interruption avec CRTL+d (POSIX) ou CTRL+z suivi de ENTER (Windows), ce script sera évalué. Ceci est basiquement identique à invoquer le CLI SAPI sans l'option -a.

À partir de PHP 8.1.0, invoquer le CLI SAPI avec l'option -a échoue, si l'extension readline n'est pas disponible.

add a note add a note

User Contributed Notes 14 notes

up
168
Ryan P
11 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
63
spencer at aninternetpresence dot net
12 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
18
Anonymous
13 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
11
#linuxmint-es
6 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
13
Anonymous
13 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
1
elijah at elijahlynn dot net
9 years 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
12 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
Gray
4 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
0
John
6 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
wheat at wheatdesign dot com
6 years ago
If you're stuck on Widows or any other machine where PHP was not compiled with readline support, one solution is to use a web-based PHP CLI. I use this in training classes, especially the sort where people bring their own laptops and I can't assume they have PHP installed. The best one I've found--partly because of the UX and partly because it's free (no credit card required) and quick to setup, is http://repl.it
up
0
alexandrebr at gmail dot com
12 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
-4
xEviL
13 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.
up
-2
alexmarcxyz at gmail dot com
5 years ago
While configuring php shell script, We need to take care of these commands, Abstract.php, Compiler.php, Indexer.php, Log.php, You can check more details about these commands at, https://www.cloudways.com/blog/php-shell-scripts-magent . Hope it will help your readers as well as I got help from your and this post.
up
-14
Shane Harter
10 years 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
To Top