Jako iż wszelakie exec(), system() passthru() itp nie radzi sobie dobrze z stderr (w razie błędu, komunikat programu nie przekazuje do zmiennej lecz wypisuje na ekran), postanowiłem napisać funkcję.
składnia:
int executeCommand ( string $command [, string &$return_out [, string &$return_err ]] )
<?php function executeCommand( $command, &$return_out, &$return_err ) { ); $cwd = '/tmp'; # working dir { # $stdout => readable handle connected to child stdout # $stdout => readable handle connected to chil stderr $stdout = stream_get_contents( $pipes[1] ); $stderr = stream_get_contents( $pipes[2] ); $return_out = $stdout; $return_err = $stderr; # now we don't need this pipes anymore, so we close them # It is important that you close any pipes before calling # proc_close in order to avoid a deadlock # return 0 if command success or >=1 if not. } } ?>
Użycie:
<?php $return_value = executeCommand( "pwd", $stdout, $stderr ); ?>
zwróci:
Kod
wartość: 0 # program został poprawnie wykonany i zwrócił 0
stdout: /root # wynik polecenia
stderr:
stdout: /root # wynik polecenia
stderr:
W przypadku gdy polecenie zwraca wartość inną niż 0, oznacza że wystąpił błąd:
<?php $return_value = executeCommand( "dupa", $stdout, $stderr ); ?>
zwróci:
Kod
wartość: 127
stdout:
stderr: sh: dupa: command not found
stdout:
stderr: sh: dupa: command not found