I am trying to create an interactive terminal to use in a project that I am working on. the idea is that I will have a web page which looks like a terminal and can use it to work with command line tools. anyway I need to use php as my service was built on php and I am familiar with it , but I couldn't get to a point where I can send multiple commands to bash (I am using bash for testing) , here is my last code snippet which seems to be able to send the given commands but I am not sure because the output of the commands is 1 !

<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


$descs = array(

    0 => array("pipe", "r"),
    1 => array("pipe", "w"),
    2 => array("file", "error.txt", "w")
);


$cmd = "/bin/bash";


$proc = proc_open($cmd, $descs, $pipe, NULL);
stream_set_blocking($pipe[0], 0);
stream_set_blocking($pipe[1], 0);

if(!$proc) {
$error_file = fopen("error.txt", "r");
echo "Error !" . fread($error_file, filesize($error_file));
fclose($error_file);
exit();
}

$status = proc_get_status($proc);
print_r($status);

if(is_resource($proc)) {

$commands = ["id", "whoami", "ls"]; 
$n = 0;
$output = "";
while($n < 3) {
    echo $commands[$n];
    usleep(1000);   
    fwrite($pipe[0], $commands[$n] . PHP_EOL );
    fflush($pipe[0]);
    usleep(1000);

    while($out = stream_get_contents($pipe[1]) && !feof($pipe[1])){

        $output .= $out ;

    }
    echo $output;   
    $n++;
}

} 
?>

I worry here that you are trying to do more than what /bin/bash alone will do. For example what happens with external commands like ls?
Read https://medium.com/swlh/the-command-line-with-ls-l-6efaf01cc4c0 to get a quick primer here.

Since /bin/bash is run on each command it would have no memory of say the chdir command so the ls after a chdir may yeild unexpected results.

There are a lot more issues here that I won't get into but if you want to get to a command line, why not ssh in?

commented: ssh is not easily scalable unlike this way where I can with GUI what each user has access to, saving state is an easy task I need to send the commands +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.