How to execute a two stage command using system() or exec()
I want to execute a command which will prompt me for some input.
I co开发者_高级运维uld figure this out by trial & error, but what's the best way to do it?
- Write a small batch file and Exec(I) that?
- Exec($command . '\r\n' . $input);
- Some thing else?
What is the command that you are trying to execute? From the comments you left it sounds like you're trying to execute PHP itself? (You passed C:\xampp\php\php.exe
to proc_open()
)
Anything that you would want to do within php.exe you can do without having to run the executable. The executable is called by Apache when you request a .php
file from the web server. Thus, if you really needed to run PHP code, you'd just code it. You wouldn't tell PHP to load the PHP interpreter. This would be silly =) Like having an English interpreter for an English speaker.
If you told us specifically the command you are trying to run then we may be able to provide a better explanation of how to accomplish it. I know one example from my own experience where I had to use proc_open()
in order to encrypt files with GPG.
$descriptors = array(
0 => array("pipe", "r"), // STDIN. Used to feed input
1 => array("pipe", "r"), // STDOUT. We are writing to it, though
2 => array("pipe", "w"), // STDERR. Used to read errors
);
// Build the command line and start the process
$cmd = '"C:/program files/gnu/gnupg/gpg.exe" --batch --no-verbose --passphrase-fd 1 --output decrypted.zip --decrypt encrypted.zip.gpg';
$gpg = proc_open( $cmd, $descriptors, $pipes);
if(is_resource($gpg)) {
// Push passphrase to custom pipe
fwrite($pipes[1], $passphrase);
fclose($pipes[1]);
proc_close($gpg);
}
Notice that for STDOUT
it says "We are writing to it, though". This code was actually my solution to a problem in Windows (Vista and XP. Not sure if 7 fixed it). Windows only allows 3 pipes to communicate with a command-line program, as opposed to UNIX which allows for the creation of MANY more (I think 256 or something). GPG generally requires four pipes to work. One for the input data (data to be encrypted/decrypted), one for the output data, one for errors, and one pipe for the password.
Since I was decrypting a file I didn't need to see the output of the program, I only needed to see if there were errors. No errors meant the output could be found in the file. Thus I ignored the output pipe and used it for sending the password. Depending on your use you may not need such a tricky solution.
exec()
isn't designed for interactive programs. To be able to talk to your subprocess, you'd want to use proc_open()
, which allows bi-directional communications.
精彩评论