0

I'm trying to run a Java program from a PHP page, using the function shell_exec(), the problem is that always return an empty response. When run a command like: ls, whoami, which, it works. I think that is related to grant access for the www-data user, but I still can not find a way to do it.

I tried to modify the file /etc/sudoers with the command sudo visudo, for add to the end of the file the next line that suppose to grant access for execute the java command:

www-data ALL=NOPASSWD: /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java

and tried with this too:

www-data ALL=NOPASSWD: /usr/bin/java

I'm using next code to invoke the java command from the php page:

$result = shell_exec('java -version');

echo $result;

I expect the output of the invoked command, but the actual output is empty.

thanks in advance.

Asuej
  • 21
  • 6
  • You could try to append 2>&1 Might be duplicate : https://stackoverflow.com/questions/15086572/php-how-to-get-shell-errors-echoed-out-to-screen – Senthil Jun 13 '19 at 00:07
  • I tried to append 2>&1 but it doesn't work. – Asuej Jun 13 '19 at 17:47

3 Answers3

1

Try this code :

exec('java -version '.' 2>&1', $result);
var_dump($result);

Ref: https://medium.com/@jnheo/setting-up-a-web-service-php-to-spit-out-results-from-a-jar-file-213667eb008a

Senthil
  • 2,156
  • 1
  • 14
  • 19
  • I tried too, but doesn't work. At this point I'm pretty sure that is something related to the user www-data privileges. – Asuej Jun 14 '19 at 01:18
  • This code works for me and gets the output : array(3) { [0]=> string(24) "java version "1.8.0_201"" [1]=> string(53) "Java(TM) SE Runtime Environment (build 1.8.0_201-b09)" [2]=> string(64) "Java HotSpot(TM) 64-Bit Server VM (build 25.201-b09, mixed mode)" }. step 1. So you need to check / ensure your path have access to java executable or give full path. ex. exec("/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java -version "." 2>&1", $result); step 2. disable safe mode in php.ini or .htaccess: Ref : https://stackoverflow.com/questions/24999673/how-to-enable-shell-exec-and-exec-on-php – Senthil Jun 14 '19 at 15:32
  • Unfortunately PHP 7.2 doesn't have Safe mode, in the php documentation says: "This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0". [Documentation ref](https://www.php.net/manual/en/features.safe-mode.php) – Asuej Jun 18 '19 at 15:24
0

I just tested and it's working

<?php 
    $out = shell_exec('java 2>&1');
    echo '<pre>'.$out.'</pre>';
?> 

Reference : In the shell, what does " 2>&1 " mean?

Vipertecpro
  • 3,056
  • 2
  • 24
  • 43
  • The command that I need to execute es `java`, and this particular command always return an empty response. – Asuej Jun 19 '19 at 14:36
0

This might work.

echo shell_exec("echo " . $command_to_exec . " > myfile.java && javac myfile.java && java myfile.java");

executes only one line of java code.

4b0
  • 21,981
  • 30
  • 95
  • 142