popen
other than exec
and the like may interact similar to a file I / O handler, probably with it will be able to get the "output "all, for example:
$response = '';
$handle = popen('apt-get remove ' . $package . ' 2>&1', 'r');
if ($handle) {
while (feof($handle) === false) {
$response .= fgets($handle); //Pega até encontrar uma quebra de linha
}
pclose($handle);
} else {
die('Erro ao executar o programa');
}
if (empty($response)) {
die('Resposta voltou vazia');
}
var_dump($response);
An example with ping
(which is something that returns the output one by one):
<?php
$response = '';
$handle = popen('ping 127.0.0.1', 'r');
if ($handle) {
while (feof($handle) === false) {
$response .= fgets($handle); //Pega até encontrar uma quebra de linha
}
pclose($handle);
} else {
die('Erro ao executar o programa');
}
if (empty($response)) {
die('Resposta voltou vazia');
}
var_dump($response);
If you want to display the result directly in the output, make echo
within while
, like this:
<?php
$response = '';
$handle = popen('ping 127.0.0.1', 'r');
if ($handle) {
while (feof($handle) === false) {
echo fgets($handle); //Pega até encontrar uma quebra de linha
}
pclose($handle);
} else {
die('Erro ao executar o programa');
}
The interesting thing is that you can already take part of the answer and with stripos
or preg_match
detect if the command is waiting for type Y / N to confirm something and customize yourself to situation you want, for example assuming you ran apt-get remove
and the terminal displayed something like:
Do you want to continue [Y / N]
The while
would lock in the fgets
that contains this command and at this point you could use a fwrite
, something like:
Note: changing the second parameter to a+
, which opens for reading and writing; puts the file pointer at the end of the handle.
$handle = popen('apt-get remove ' . $package . ' 2>&1', 'a+');
if ($handle) {
while (feof($handle) === false) {
$response = trim(fgets($handle));
if (stripos($response, 'do you want to continue') !== false) {
fwrite($handle, "Y\n");// O \n é para enviar a quebra de linha que creio ser necessária para disparar
}
}
pclose($handle);
} else {
die('Erro ao executar o programa');
}