PHP Interactive Interpreter

The PHP interpreter supports running it in interactive mode by using the --interactive (short equivalent: -a) command-line switch. Running an interactive PHP shell can be useful when you need to quickly try code snippets. But, for this mode to be fully functional, PHP has to be compiled with readline support. Unfortunately, on CentOS PHP has not been compiled this way.

You can check the PHP compile-time configuration switches, by invoking the following command:

php --info | grep -i 'configure command'

While searching for a solution about this, I ran across an interesting project, phpa. From the developer:

phpa is an interactive command line shell for PHP.

It is a replacement for the interactive mode of the PHP interpreter (php -a), hence the name.

This software is public domain.

Before using it, make sure php-readline is installed:

yum install php-readline

I downloaded phpa and set the executable bit as shown below:

wget -O - http://david.acz.org/phpa/phpa.txt > ~/bin/phpa
chmod +x ~/bin/phpa

I also had to fix the bad shebang:

sed -i 's#/usr/local/bin/php#/usr/bin/php#' ~/bin/phpa

Finally, an interactive PHP shell! Now running code snippets from the PHP manual is fun:

[rocky@arena ~]$ phpa
PHP 5.1.6 (cli) (Jan 13 2010 17:05:38) [Linux]
>>> $arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42));
>>>
>>> echo $arr["somearray"][6];    // 5
5
>>> echo $arr["somearray"][13];   // 9
9
>>> echo $arr["somearray"]["a"];  // 42
42
>>>

Enjoy your new PHP interactive interpreter!

PHP Interactive Interpreter by George Notaras, unless otherwise expressly stated, is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Copyright © 2010 - Some Rights Reserved

About George Notaras

George Notaras is the editor of G-Loaded Journal, a technical blog about Free and Open-Source Software. George is a GNU/Linux enthusiast, a self-taught programmer and system administrator. He strongly believes that "knowledge is power" and has created this web site to share the IT knowledge and experience he has gained over the years with other people. George primarily uses CentOS and Fedora and spends some of his spare time developing open-source software. Follow George on Twitter: @gnotaras

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>