views:

765

answers:

5

I have a website and want to be able to allow the user to run a Java file on the server from the website.

I want the user to click a button which will run the Java file on the server AND anything printed to standard-out by the Java program will be printed out on the website for the user to see.

How can this be done (call Java program from PHP and feed the standard out from the Java file back to the PHP website in real time)?

Update:

Thanks for the answers on how to run the Java program from PHP. However I also want to be able, as the Java program is printing to stdout where it will be printing out a lot of text as it is executing, to be able to print this out on the webpage so that the user can see what stage the Java program is in its execution.

How can this be done and does it require any additional AJAX or JavaScript or anything like that?

+3  A: 

Check out exec and the other program execution functions. But do this very carefully, or it's a recipe for exploits.

Bobby Jack
A: 

Is the passthru function of any use?

http://www.php.net/manual/en/function.passthru.php

brianjd
+3  A: 

Since you mention real time I would suggest setting up a PHP to Java Bridge. Initializing the JVM at each request takes up a lot of resources.

PHP/Java Bridge

The PHP/Java Bridge is an implementation of a streaming, XML-based network protocol, which can be used to connect a native script engine, for example PHP, Scheme or Python, with a Java or ECMA 335 virtual machine. It is up to 50 times faster than local RPC via SOAP, requires less resources on the web-server side. It is faster and more reliable than direct communication via the Java Native Interface, and it requires no additional components to invoke Java procedures from PHP or PHP procedures from Java.

Peter Lindqvist
+1  A: 

The PHP exec() function is the way to go, but obviously you should be very careful in what you allow to executed (don't rely on user input) as it could potentially compromise your entire server.

Calling the Java application launcher using exec, you can execute any Java application from PHP, e.g.

<?php exec("java -jar file.jar arguments",$output); ?>
James
+1  A: 

I would rather wrap the Java class in a Java applet, which can then be invoked from a javascript call on the client side : see http://www.rgagnon.com/javadetails/java-0170.html

Otherwise, if the call throws a lot of text to the standard output or the class has to be run on the server because of system dependencies, calling from php exec is the way to go, but you will probably need something like cometd to display the text on the client in real time. There are implementations for various javascript toolkits such as Dojo or jQuery.

For the server side, there seems to be a cometd implementation in php here.

I hope this helps...

Philippe

Philippe