1

I want to connect to java via php and print the result out in php. Now I want to send a parameter to java and return it to php to see how it works. How can I do this? I have this code so far:

PHP:

exec("java jar/name.jar", $output);
print_r($output);

Java:

public class Main {
    public static void main(String[] args) {
        System.out.print(args[0]);
    }
}

The result is

Array ( )

4 Answers 4

10

Do

exec("/full/path/to/java -jar jar/name.jar 2>&1", $output);
print_r($output);

because

  • your PHP env probably doesn't have java executable defined in the path (and it shouldn't, either)
  • jar files are executed with java -jar
  • you'll want 2>&1 to be able to see error messages in the output (redirect from stderr to stdout)
Sign up to request clarification or add additional context in comments.

2 Comments

third point was very useful without it some program do not $output anything, dont know why !
@AbhishekK because it prints the errors on stderr, and normally only stdout is captured, where normal output goes
1

Your java program expects atleast one argument, but the php code doesn't give it, so change your

exec('java jar/name.jar', $output);

to

exec('java jar/name.jar some_value', $output);

Edit:

The reason why you got Array ( ) when you did not specify an argument is probably because the error's send by java are send to stderr, and $output only gets data from stdout

4 Comments

I did what you said but the array is also empty.
@bw2801 are you sure you got the java jar/name.jar part correct? it would mean that relative to your php file the file name.jar is in the map jar. The way I tested it was: create test.php and Main.java in the same directory with your code. run javac Main.java and run php test.php (test.php had exec('java Main some_value', $output);
the folder "jar" is in the same directory as the php file.
You can try to use php -a, this will open php in interactive mode, then type exec('java jar/name.jar some_value', $output); perhaps it'll give you some more information
0

Consider using a RESTful design. Put the Java program at a URL and read from the URL with PHP *file_get_contents()*. Anything the Java program writes to the browser output stream will be visible in the PHP variable that is loaded by that function.

Comments

0

If you really want to integrate native Java code into your PHP application, the PHP/Java Bridge may be able to solve that in a better way than having to go through exec()-ing java code.

Creating a small service for your Java functionality is however the preferred way to go, then exposing those features through a small web based API (with JSON as the exchange format preferably).

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.