1

First let's run the command via terminal:

$ echo 1; /etc/init.d/apache3 restart; echo 2;

result.. ( apache3 on purpose to see an error )

1
bash: /etc/init.d/apache3: No such file or directory
2

awsome.

now let's run this via php..

<?php

$command = "echo 1; /etc/init.d/apache3 restart; echo 2; 2>&1";
$response = shell_exec("$command");
echo $response;

?>

all I see on the browser is: 1 2

I tried all sorts of things. replaced the semi colons with "&&".. tried all the php stuff such as..

passthru()
exec()
system()
popen()

i tried it all pretty much. been hours.. can not get it to show me the same stuff i see via terminal.

0

3 Answers 3

1

You have to use 2>&1 after the restart command

Your command :

$command = "echo 1; /etc/init.d/apache3 restart; echo 2; 2>&1";

yours has "2>&1" at the end which has no use.

Also you will add to 2>&1 after each command in case others uses STDERR

$command = "echo 1; /etc/init.d/apache3 restart 2>&1; echo 2 ";
Sign up to request clarification or add additional context in comments.

Comments

1

Consider using exec. The basis function only returns the first line of the output:

$response = exec("$command"); // just the first line

But use the additional parameters to capture both the output (as an array) and the return value

$retval = NULL;
$output = NULL;
$response = shell_exec("$command", $output, $retval); // last two params are passed by reference and modified by the command

Also, as user993553 posted, the output captured by these cli functions in PHP will usually just return stdout and not stderr. You can append " 2>&1" to any given command (note the space before the 2) in order to route stderr into the output.

That said, your function becomes:

$command = "echo 1; /etc/init.d/apache3 restart 2>&1; echo 2;";
$retval = NULL;
$output = NULL;
$response = exec($command, $output, $retval);
var_dump($output);

and the output:

array(3) {
  [0] =>
  string(1) "1"
  [1] =>
  string(37) "sh: 1: /etc/init.d/apache3: not found"
  [2] =>
  string(1) "2"
}

EDIT: you can also check $retval for an error condition. If it's not empty or zero, then signifies an error.

Comments

0

From the manual of shell_exec:

ALSO, note that shell_exec() does not grab STDERR, so use "2>&1" to redirect it to STDOUT and catch it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.