Skip to content
Advertisement

How to give input to java program and continue with execution using PHP?

I want to execute java programs using php code. When i write the below code, the program written in the editor is getting compiled and executed successfully.

JavaScript

Note: $output and $check variables contains required input to compile & run

But, when I try to execute java programs where we need to input some data to contine with the execution, the above code doesn’t works. For example, consider the JavaScannerExample in the link: http://alvinalexander.com/java/edu/pj/pj010005

To execute the program in the link, I guess I need some interactive console to accept the input and continue with program execution. Please suggest me how to achieve this using php?

Update:

@Chris.. Tried proc_open command as suggested. See my code below:

PHP Code

JavaScript

Java Code

JavaScript

PHP Output

JavaScript

Could you please check and let me know where did I went wrong?


Update2:

@Chris.. Thanks for your suggestion. It helped me get the output.

Here is the modified php code:

JavaScript

This is the result I am getting.

JavaScript

There are multiple problems with this type of result. First I am trying to build an interactive console. So for the above example, the pipes need to work in parallel. However, I am not able to retrieve pipes[1] until I close pipes[0]. Because if I get the value of pipes[1] earlier in the code the program is hanging. In this scenario. First I need to be able to read the input which is “Enter your name:” Then enter input which is “Mark”. Next steps are similar I need to get the text “Enter age:” and enter input “32”. finally I need to get the final output which is “Mark, your age is 32” and detect the program is finished and then close both the pipes. Is this possible?

Advertisement

Answer

Use proc_open instead of exec. It can be used to retrieve a pipe to stdin which can be used to provide input to your Java application. The first example on the proc_open manual page demonstrates how to do this.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement