GP cyborg
GP cyborg

Reputation: 198

PHP - How to keep a Command Shell open for executing multiple commands?

Hi I am trying to execute multiple commands using PHP on a windows machine. I tried this code:

<?php
$output= shell_exec("powershell.exe");
$output2= shell_exec("write-host gokul");
shell_exec("exit");
echo( '<pre>' );
echo( $output );
echo( $output2 );
echo( '</pre>' );
?>

PHP executes each command with a new shell and closes it on completion!

I understand that each 'shell_exec' creates a new shell and control waits till command execution completes. How can I create a shell that stays open in the background till I close it ?

Am not sure if 'proc_open' or 'popen' can help ?

UPDATE when I try PROC_OPEN()

$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "error.txt", "a") // stderr is a file to write to
);    
$process = proc_open('cmd.exe', $descriptorspec, $pipes);

if (is_resource($process)) {
    fwrite($pipes[0], 'dir');
    fwrite($pipes[0], 'powershell.exe');
    fwrite($pipes[0], 'write-host gokul');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    proc_close($process);
}

It prints only the prompt. Can I really use proc_open to execute multiple commands ? If so, how?

Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\wamp\bin\apache\Apache2.2.17>More?

Upvotes: 2

Views: 3054

Answers (1)

hek2mgl
hek2mgl

Reputation: 157967

Using proc_open is the correct attempt but you need to finish every command with a new line character. Like if you would type the command manually in a shell session.

It should look like this:

fwrite($pipes[0], 'dir' . PHP_EOL);
fwrite($pipes[0], 'powershell.exe' . PHP_EOL);
fwrite($pipes[0], 'write-host gokul' . PHP_EOL);

Upvotes: 3

Related Questions