Running shell_exec(‘which java’) in PHP return nothing

Tags: , ,

If I run

which java

from the command line I get the proper input (/usr/java/…/bin/java). However if I run it in a php script:

  echo 'java. ' . shell_exec('which java');
  echo 'ls. ' . shell_exec('which ls');

nothing gets printed out for which java but I get the proper results for which ls…


Two things were needed:

  • the full path to the JVM (it wasn’t set in the environment)
  • ” 2>&1″ at the end of the command line.

So for example:

echo shell_exec('/usr/java/jdk6/bin/java -cp myJars.jar MyMainClass arg1 2>&1");

Source: stackoverflow