My website needs PHP to run a Java program in the background. So, PHP issues exec()
method to let Java do all the work. The implementation works fine on Windows, but completely failed on Ubuntu. While exec()
doesn't work, a stand-alone test with console works just fine.
I've setup a test.php
to narrow down the problem:
<?php
$output = exec("java -cp ~/path/to/java/class/file/folder Hello 2>&1");
//$output = exec("whoami");
echo $output;
?>
The Hello.java
is simply:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
By running test.php
on localhost, it shows:
Error: Could not find or load main class Hello
I tried to narrow down the cause of the error, and my thought went like this:
exec()
itself is problematic:
unlikely, sincewhoami
prints out apache-user as expected.
- what the error message means:
I searched about this error. Post like this one talks about it is caused by the absence of classpath. It's not the case for me either, because in console it works. So the error message means nothing (does it?)
- user/group permission:
Is it possible that apache-user is not permitted to run the class file?
I checked, and found the permission code ofHello.class
to berw-r--r--
, owned byapache-user:webmasters
.
But, even if no one hasx
permission of the file, in console I can still run it (using my own user).
I'm not sure about the situation here. But my understanding is that by running java program, it is reallyJVM
executing it (or something else); so the permission ofHello.class
doesn't matter.
I found another post has a similar situation. But its solution - specifying full path to Java bin/usr/bin/java
- doesn't work for me...
What is causing the error?
Can anyone help? Detailed solution is appreciated! I'm a newbie @_@
Many thanks!!!