PHP running java jar files with parameters as php variables

Go To


Hi I am attempting to execute a jar from PHP 5

Here is the code I am executing:

$command = '"java -jar WEB-INF\\lib\\FileReceiver.jar '.$address.' '.$service_port.' \"'.$command.'\" \"'.$filePath.'\""';
exec($command, $out);

But the jar is not being executed. I had logged the $command variable in firebug and took the output and inserted into the code such as:

exec("java -jar WEB-INF\lib\FileReceiver.jar 2018 \"docs/document.txt \" \"C:\\apache-tomcat-7.0.26\\webapps\\test\\downloads\\doument.txt\"", $out);

gives the correct output. I dont understand why hard coding it works but the variable which contains the same information does not.

Could someone help me out?


2012-04-04 02:30
by ßee
are you sure $adress $service_port $command and $filepath have the right values - NoName 2012-04-04 02:33
you need to show \" , you should write \ - saturngod 2012-04-04 02:33
@Shingetsu yes I am sure, I literally copied whats in the variable $command from firePHP console and pasted it - ßee 2012-04-04 02:47


try like this

$command = escapeshellarg($address).' '.escapeshellarg($service_port).' '.escapeshellarg($command).' '.escapeshellarg($filePath).' ';

exec('java -jar WEB-INF\\lib\\FileReceiver.jar '.$command, $out);
2012-04-04 02:34
by saturngod
same issue if I hard code what is contained in the variable its worksm but if I pass the variable, the jar is not executing. Thank you for your quick reply. Do you have any other suggestions - ßee 2012-04-04 02:44
echo $command; and see the resul - saturngod 2012-04-04 03:44
I tried it and the result is correct. I replaced $command with the echo result in exec and it works correctly. I am totally confused why having the variable in the exec will not execute - ßee 2012-04-04 04:30
@ßee , try with escapeshellar - saturngod 2012-04-04 04:49
I tired that too just adds a space after the double quotes at the beginning and end and removed the quotes in the middle which would make it worse. Either way the jar did not execut - ßee 2012-04-04 05:06
Tried the encapsulating each component like you did above but nothing, the jar is not even being run. I even tried surrounding the entire command in quotes like exec('"java -jar WEB-INF\lib\FileReceiver.jar '.$command.'"', $out); with no succes - ßee 2012-04-04 14:12
Thank you so much for your help. I just figured out the problem. the $command had a \n character which stopped it from executing in the jar file - ßee 2012-04-04 14:34


You're over-escaping the double quotes in your first snippet.

You're using single quotes for the literal string delimiter, so you don't need to escape the double quote.

Also, the final '\""' should be '"'

2012-04-04 02:36
by Ariel