I am trying to run a java program using php script.
First, php displays a form where users input two values: Price and Sales Tax Rate. Next, it extracts the values and passes it to a java program (precompiled as .class file).
I am uncertain as to where the output is printed if at all the java code is working. My ultimate goal is to display the result to the user in an html page.
I upload my file contents to my web server and try to run it from there.
How can I use shell_exec or exec to run java code? I need to pass the parameters (price, salesTax) to shell_exec. Where is the returned output stored?
PHP code:
> <?php
>
> $salesTaxForm = <<<SalesTaxForm
>
> <form action="SalesTaxInterface.php" method="post">
>
> Price (ex. 42.56):<br>
>
> <input type="text" name="price" size="15" maxlength="15"
> value=""><br>
>
> Sales Tax rate (ex. 0.06):<br>
>
> <input type="text" name="tax" size="15" maxlength="15"
> value=""><br>
>
> <input type="submit" name="submit" value="Calculate!">
>
> </form>
>
> SalesTaxForm;
>
> if (! isset($submit)) :
>
> echo $salesTaxForm;
>
> else : $salesTax = new Java("SalesTax");
>
> $price = (double) $price; $tax = (double) $tax;
>
> print $salesTax->SalesTax($price, $tax);
>
> endif;
>
> ?>
Java Code:
import java.util.*; import java.text.*; public class SalesTax { public String SalesTax(double price, double salesTax) { double tax = price * salesTax; NumberFormat numberFormatter; numberFormatter = NumberFormat.getCurrencyInstance(); String priceOut = numberFormatter.format(price); String taxOut = numberFormatter.format(tax); numberFormatter = NumberFormat.getPercentInstance(); String salesTaxOut = numberFormatter.format(salesTax); String str = "A sales Tax of " + salesTaxOut + " on " + priceOut + " equals " + taxOut + "."; return str; } }
The IBM® sMash Runtime for PHP provides access to Java™ classes and functionality from PHP. This Java Bridge can instantiate Java classes and call their methods.
shell-exec executes the comand that you pass to it. To use this, you have to add a Main method to your class, and pass the properties like arguments in the comand line, so at the end it should look like this:
This is code that you have to execute on php
$output = shell_exec('java SalesTax 10.0 20.0');
Where SalesTax is your java class, 10.0 is the first argument, and 20.0 the second.
Your main method should be something like this
public static void main(String args[]){
double price = Double.valueOf(args[0]);
double salesTax = Double.valueOf(args[1]);
String output = SalesTax(price,salesTax);
System.out.println(output);
}
It's a very simple implementation, you should still add validations and some other stuff, but I think that it's the main idea. Maybe it should be easier to just port it to php.
I hope that you find this helpful. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With