4

Lets take this command for example:

$command = "echo '/just/for/the/test /heh/' | awk '//just// {print $1}'";

When directly copying it inside shell, I get the following error:

awk: cmd. line:1: //just// {print $1}
awk: cmd. line:1:         ^ unterminated regexp

But, when I exec() it, I get status code 1 with no output:

exec($command, $output, $status);

var_dump( $command, $output, $status );

// string(69) "echo '/just/for/the/test /heh/' | awk '//just// {print $1}'"
// array(0) { }
// int(1)

How to retrieve the STDERR part of exec?

tomsseisums
  • 13,168
  • 19
  • 83
  • 145

2 Answers2

5

You should redirect stderr to stdout somehow like this

$stout = exec($command . " 2>&1", $output, $status);

See also here PHP StdErr after Exec()

Community
  • 1
  • 1
Benjamin Seiller
  • 2,875
  • 2
  • 32
  • 42
  • 1
    Thanks for the link, that one has hell of an answer on the subject. Bad thing it didn't show up on related questions when I asked. *Also, your answer is a tad faster than @Vlad's + you have less rep., so - accepted.* – tomsseisums Sep 18 '12 at 07:45
  • Well, thank you :) I actually thought his answer was faster & also more extensive. But I won't complain for sure. – Benjamin Seiller Sep 19 '12 at 07:34
3

with exec() the only way i can think of is to redirect STDERR to STDOUT in the command you are executing, like:

$command = "echo '/just/for/the/test /heh/' | awk '//just// {print $1}' 2>&1";

an alternative to exec() is to use the proc_open() family of function. With proc_open() you execute the command and open file pointers to STDIN, STDOUT and STDERR from which you can read / write

see the manual for more info

Vlad Balmos
  • 3,372
  • 19
  • 34