note 52826 added to function.shell-exec
| From: | dk at brightbyte dot de | Date: | Fri, 13 May 2005 20:25:44 +0000 |
| Subject: | note 52826 added to function.shell-exec | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-89395@lists.php.net to get a copy of this message | ||
her's a function that is similar to shell_exec but captures both stdout and stderr. It's
much more complicated than using 2>&1, but it's independent of the shell and should work
on windows, too. It uses proc_open with stream_select and non-blocking streams to read stdout and
stderr concurrently. It is not guarantied that the lines appear in the correct order or that they
are not intermingeled - but it did not happened when I tested it. So, here goes:
<?php
function runExternal($cmd,&$code) {
$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("pipe", "w") // stderr is a file to write to
);
$pipes= array();
$process = proc_open($cmd, $descriptorspec, $pipes);
$output= "";
if (!is_resource($process)) return false;
#close child's input imidiately
fclose($pipes[0]);
stream_set_blocking($pipes[1],false);
stream_set_blocking($pipes[2],false);
$todo= array($pipes[1],$pipes[2]);
while( true ) {
$read= array();
if( !feof($pipes[1]) ) $read[]= $pipes[1];
if( !feof($pipes[2]) ) $read[]= $pipes[2];
if (!$read) break;
$ready= stream_select($read, $write=NULL, $ex= NULL, 2);
if ($ready === false) {
break; #should never happen - something died
}
foreach ($read as $r) {
$s= fread($r,1024);
$output.= $s;
}
}
fclose($pipes[1]);
fclose($pipes[2]);
$code= proc_close($process);
return $output;
}
?>
here is how to use it:
<?php
$result= runExternal("ls -l some-file.txt",$code);
print "<pre>";
print $result;
print "</pre>\n";
print "<b>code: $code</b>\n";
?>
enjoy :-)
----
Manual Page -- http://www.php.net/manual/en/function.shell-exec.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+52826
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52826&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52826&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52826&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52826&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52826&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+52826&report=yes
Search -- http://master.php.net/manage/user-notes.php