Search code examples
phpsystemshell-execphp-7.4

PHP system(), exec(), and shell_exec() not returning output


I want to find the correct path of MySQL. However, the output of this command is empty. According to the manual for PHP's exec() command, this command should capture the output of the shell command.

<?php
$cmd = "which mysql 2>&1;";
print($cmd."<br>");
exec($cmd, $output, $retval);
var_dump($output);
print("<br>");
var_dump($retval);
?>

OUTPUT:

which mysql 2>&1;
array(0) { }  
int(1)

COMMAND LINE OUTPUT:

$ which mysql 2>&1;
/usr/local/mysql/bin/mysql

Why does the command error? Why variable not contain the output for error since command specifies 2>&1?


Solution

  • I think that the issue is not that you not get the output of the executed command, but which fails to find mysql. Using exec you can get the return status of your command, where 0 means successful, and other values indicate an error.

    $output = exec($cmd, $output, $retval);
    var_dump($output);
    var_dump($retval);
    

    If the $retval is 1 that would mean which doesn't find the mysql binary, and returns an empty line.