Sunday, March 30, 2008

PHP Interactive Shell with one line of PHP

PHP lacks built in functionality for an interactive Shell such as built into Python, Perl etc. You can execute PHP from the shell using the php -r but it isn't interactive. Using php -a didn't work for me on both Win and Linux, so I wrote this single line PHP script that will allow an "interactive" PHP Shell.

#!/usr/bin/php
<?php while (1) {  fputs(STDOUT, "\n\-PHP$ "); eval(trim(fgets(STDIN))); } ?>
There it is on 1 line, plus the Shebang.

To use it just copy the code and save to a file. You don't need to give the file an extension. For example I named it iphp. Then you execute it in the shell using ./iphp. You should get $PHP as your prompt:
-bash-3.00$ ./iphp

$PHP

Now you type in your PHP commands such as:
-bash-3.00$ ./iphp

$PHP $result = 1+1;

$PHP echo $result;
2
$PHP
Notice how you can save a variable, and reference it later. This is the same for a mysql connection, file pointer etc.

When you're done, just type in exit;.

-bash-3.00$ ./iphp

$PHP $result = 1+1;

$PHP echo $result;
2
$PHP exit;
bash-3.00$

Update: April 16, 2008

In further tests:

php -a 
into the shell on Linux (Ubuntu 7.05) running PHP 5.2.4-2 (cli) works and takes you into interactive mode. I had previously tested this with PHP 5.1.6 (cli) on Linux (CentOS 3.9 and 4.6) and couldn't get it to work. The same with PHP4 and PHP5 (cli and module) on Windows.

5 comments:

Todd said...

Very cool! Thank you for the concise code snippet.

In Perl I was able to simulate a GET request on the command line but could not find a quick and dirty way to do it in PHP command line mode.

Following is a transcript of a session simulating the $_GET array and calling a script which returned the results as JSON.


>php iphp.php

\-PHP$ $_GET = array('id'=>1);

\-PHP$ include('myscript.php');
{
"id":"1",
"title":"Core Systems",
"htmlFile":"core_systems.html",
"imageFile":"core_systems.jpg"
}
\-PHP$

bucabay said...

Hi Todd,

You could just use file_get_contents();

eg: echo file_get_contents('http://example.com/');

see: http://www.php.net/file_get_contents

Only works if PHP configuration allows it. I believe the directive is allow_url_fopen.

Otherwise you need to use CURL.

fabio said...

Thank you so much for this! php -a isn't working for me either even though i'm using php 5.3.5!!! i think xampp doesn't compile php with the directive to allow interective shell

man9ar00 said...

Does this method work on Windows via the windows command line? Or would we need Cygwin for it on Windows?

bucabay said...

works fine with windows..