Вопрос

Hi I'm new to programming in PHP. I use a WAMP server -> Apache version 2.4.4 and PHP version 5.4.16

I want to execute java program from php script, here's my java program

   file : test.java
    import java.io.*; 
    public class test {
        public static void main(String args[]) {
            System.out.println("Hello World");
        }
    }

I used

exec("javac test.java");
exec(java test);

and it's no use. So then I tried to put the command code in "runfile.bat"

javac test.java > error.txt
java test > output.txt

when I execute runfile.bat by left clicking twice, it run perfectly and there's text "Hello World" in output.txt

then I try from PHP:

exec('start /B /C runfile.bat');

... and output.txt has nothing in it.

Это было полезно?

Решение 2

You probably want to fully-qualify paths here (especially if this is a web application):

exec("javac test.java");
exec("java test");

Something more like:

exec("/path/to/javac /and/the/path/to/test.java");
exec("/path/to/java /and/the/path/to/test");

It's possible that it's "running" but the working directory isn't correct, so maybe it can't find the javac and java executables or can find them but can't find test.java. When you run these things manually the executables are in your path and the file is in your working directory, but both of those may not be true for the PHP context.

Aside from that, it's also good practice to fully-qualify things anyway. It's more explicit and less prone to error (or even exploit, if a user were to somehow upload a javac executable of their own to your website they could execute it with elevated permissions using your script).

Другие советы

Definitely PHP's exec() would do.

<?php
exec('java test', $output, $return_var);

// `$output` captures the output of command executed
print_r($output);

// Generally `$return_var` becomes 0 if the command was successful
if (0 == $return_var) {
    // Command successfull
}
?>

PS: Make sure your Java class-paths are correct. Always look for PHP Manual -- which the best ever manual I've ever seen.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top