Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Java program and get output in PHP?

Tags:

php

exec

I'd like to run something like (in myProgram.sh):

java -cp whatever.jar com.my.program $1

within PHP and read the output.

So far I have something like:

$processOrderCommand = 'bash -c "exec nohup setsid /myProgram.sh ' . $arg1 . ' > /dev/null 2>&1 &"';
exec($processOrderCommand);

But what I'd really like is to be able to get the output of the java program within the PHP script and not just execute it as another thread.

How can this be done?

like image 443
Stephane Grenier Avatar asked Sep 24 '10 17:09

Stephane Grenier


1 Answers

You can do this :

exec($processOrderCommand, $output);

From the documentation :

If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n, is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec().

For a better control on your execution you can take a look at proc_open()


Resources :

  • php.net - exec()
  • php.net - proc_open()
like image 51
Colin Hebert Avatar answered Oct 21 '22 06:10

Colin Hebert