Witam,
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 ]] )

  1. <?php
  2. function executeCommand( $command, &$return_out, &$return_err )
  3. {
  4.        $descriptorspec = array(
  5.                1 => array("pipe", "w"),  # stdout
  6.                2 => array("pipe", "w")   # stdin
  7.        );
  8.  
  9.        $cwd = '/tmp'; # working dir
  10.  
  11.  
  12.        $process = proc_open( $command, $descriptorspec, $pipes, $cwd, NULL );
  13.  
  14.        if( is_resource( $process ) )
  15.        {
  16.                # $stdout => readable handle connected to child stdout
  17.                # $stdout => readable handle connected to chil stderr
  18.                $stdout = stream_get_contents( $pipes[1] );
  19.                $stderr = stream_get_contents( $pipes[2] );
  20.  
  21.                $return_out = $stdout;
  22.                $return_err = $stderr;
  23.  
  24.                # now we don't need this pipes anymore, so we close them
  25.                fclose( $pipes[1] );
  26.                fclose( $pipes[2] );
  27.  
  28.                # It is important that you close any pipes before calling
  29.                # proc_close in order to avoid a deadlock
  30.                # return 0 if command success or >=1 if not.
  31.                return proc_close( $process );
  32.        }
  33.  
  34. }
  35. ?>


Użycie:
  1. <?php
  2.  
  3. $return_value = executeCommand( "pwd", $stdout, $stderr );
  4. print "wartość: " . $return_value . "\n";
  5. print "stdout: " . $stdout . "\n";
  6. print "stderr: " . $stderr . "\n";
  7.  
  8. ?>


zwróci:
Kod
wartość: 0 # program został poprawnie wykonany i zwrócił 0
stdout: /root # wynik polecenia
stderr:


W przypadku gdy polecenie zwraca wartość inną niż 0, oznacza że wystąpił błąd:
  1. <?php
  2.  
  3. $return_value = executeCommand( "dupa", $stdout, $stderr );
  4. print "wartość: " . $return_value . "\n";
  5. print "stdout: " . $stdout . "\n";
  6. print "stderr: " . $stderr . "\n";
  7.  
  8. ?>


zwróci:
Kod
wartość: 127
stdout:
stderr: sh: dupa: command not found