Published on May 1 2013 in Java PHP/Perl/Python

For PHP to find Java and see related environment variables you need to set the variables explicitly in your PHP code or use Java related variables predefined in your .bashrc or similar shell resource file.

As fastcgi subprocesses do not start separate shells, they do not read shell resource scripts (e.g. .bashrc) from your home directory. They use environment variables of parent process instead and evidently your expected Java related variables will not be there. You will need to define needed variables in your php script, for example:

echo 'test without shell (variables defined in php)';
$JAVA_HOME = "/opt/jdk1.6.0_43";
$PATH = "$JAVA_HOME/bin:".getenv('PATH');
$r=`echo $JAVA_HOME; which java; java -version 2>&1`;
echo "<pre>$r</pre>";

Another solution is to call bash explicitly in shell_exec (or with backticks) as interactive shell and then it will read in your .bashrc defined variables like JAVA_HOME, JAVA_OPTS and PATH:

echo 'test with interactive shell (variables in ~/.bashrc)';
$r=`bash -ic 'echo \$JAVA_HOME; which java; java -version 2>&1'`;
echo "<pre>$r</pre>";
echo 'another variant of above';
exec("bash -ic 'echo \$JAVA_HOME; which java; java -version 2>&1'", &$myOutput, &$result);
echo "<pre>".join("<br/>",$myOutput)."<br/>result = ".$result."</pre>";

Note: Java messages go to stderr so they must be redirected to stdin to be catched by shell_exec and printed by the PHP script thus the 2>&1 redirection.

The same way you may define CLASSPATH variable so that your jars are found by java process. Use full paths for other input/output files provided in java command line (for example a file with data to be processed or a file where results will be stored).

On a shared hosting server you have limited JVM related resources like heap and PermGen memory so you should also set correct JAVA_OPTS if you are not using the 'bash interactive' method.

Yet another approach to get Java and its parameters visible by PHP is to source a file (commonly known as envvars in case of Apache) that sets or modifies environment variables when Apache is started but this solution only makes sense on a VPS or dedciated server as it makes global changes affecting all PHP subprocesses.

And last but not least there is php-java bridge project that you may also use for executing Java code from PHP - it provides better integration between the languages. See more in How to run PHP applications in Tomcat 7 with PHP-Java bridge?


If you happen to get

Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine."

make sure that heap limits are correctly passed to the java command. Try this:

$r=`bash -ic 'echo $a_php_var; echo \$JAVA_HOME; echo \$JAVA_OPTS; which java; java \$JAVA_OPTS -version 2>&1'`;
echo "<pre>$r</pre>";

to verify it.