Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

I can run java file using command line:

java HelloWorld

Now I am trying to run a HelloWorld.class file in php script using exec(). The problem is, when I run commands like:

<?php exec("which java", $output); print_r($output); ?>

it print correct result, but when I tried to run java file:

<?php exec("java HelloWorld", $output); print_r($output); ?>

it only print out Array().

The content of HelloWorld.java is:

public class HelloWorld{

public static void main(String []args){
    System.out.println("Hello World!!!!");
 }
}

And I have already create the HelloWorld.class file using command line javac HelloWorld.

So how can I fix it?

PS. I changed the command into:

<?php exec("java HelloWorld 2>&1", $output);
   print_r($output); ?>

and I got Array ( [0] => Error: Could not find or load main class HelloWorld )

Does anyone know what the problem is?

Ok, I've fixed it.

I forget to set classpath when I use php exec().

So, the code should be:

<?php exec("java -cp '/var/www/html/run' HelloWorld 2>&1", $output);
      print_r($output);?>
share|improve this question
    
Do you want the php to execute the java program and print out Hello World!!!! or just to print out java HelloWorld – Zach Jul 20 '14 at 16:05
    
print out Hello World!!! – user3794582 Jul 20 '14 at 16:08
    
Try executing javac HelloWorld and then java HelloWorld so that the program you wrote compiles first – Zach Jul 20 '14 at 16:10
    
Yes, I've done this step. I have HelloWorld.java and I've already create a HelloWorld.class file using command line "javac HelloWorld". Do, you mean I should add exec("javac HelloWorld"); in php file even when I've already have .class file? – user3794582 Jul 20 '14 at 16:16
    
No, I guess not if you already have a compiled version of the program, as long as the .class file is up to date. – Zach Jul 20 '14 at 16:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.