ONLamp.com    
 Published on ONLamp.com (http://www.onlamp.com/)
 See this if you're having trouble printing code examples


PHP and Java

by W.J. Gilmore
06/14/2001

Do PHP developers ever sleep? I'm starting to wonder what these caffeine-entranced insomniacs are going to think of next. I'm asking this question because I can't seem to understand how PHP always seems to have just the right extension to accomplish the task at-hand. Mathematical functions? No problem. Databasing? Simple. Butter my toast? Well, we're not that far yet, but give some PHP programmer a spare weekend locked away in his office, and some script will soon be asking me "Is margarine okay?". You just wait and see.

Why am I ranting about this? It's because I've recently begun messing around with PHP 4.0's Java extension, and I'm in awe over the whole new dimension that using Java classes within PHP code offers. As if it's not enough that I'm using my favorite scripting language, I can also use my other favorite language simultaneously? What more could a geek like me ask for?

Okay, enough babbling. In this article, I'm going to introduce this great new extension in detail, providing not only information regarding the necessary steps to configure Java support for PHP, but also highlighting several examples that are geared toward showing you just what is possible when intertwining these two languages.

Configuration

Java support is not native to the PHP 4.0 distribution; therefore, you'll need to perform a few installation and configuration steps in order to use Java and PHP together. However, these steps are rather trivial and should only take a few minutes to accomplish.

JDK installation

First off, you'll want to install the JDK. For purposes of this article, I used JDK 1.2.2, and will refer to the JDK throughout this article using this version title. However, you are free to use any version you choose (1.1.8, 1.2, or 1.3). You can find the JDK at http://java.sun.com. Simply follow the directions that are provided with the respective platform installation, and you will have this up and running in no time. Once you've installed the JDK, move on to the following sections.

Non-Windows users

You'll need to reconfigure PHP using the following option:

./configure -with-java [-other-configuration-options]

If you are unfamiliar with how PHP is configured and installed on a non-Windows system, I would suggest checking out Darrell Brogdon's excellent article "Basic Installation of PHP on a Unix System".

Windows users

After installing the JDK, I would highly recommend adding the JDK path to your environment path. This is accomplished by opening autoexec.bat and adding the line:

PATH=%PATH%;C\jdk1.2.2\bin

Downloading the Win32 Java extensions

If you're a Windows user, you'll also need PHP's Win32 Java extensions (available for the 1.1.8, 1.2.2, and 1.3 versions). Be sure to download the one that matches the JDK version you installed. These extensions are packaged as a Zip file. Once downloaded, unzip the file, and extract it to a folder named jdkx.x.x (the x's denoting your version number) within the folder where PHP is installed on your machine. Two of these files, namely jawt.php and jver.php are just test files, so you can ignore them for the moment. The file php_java.dll should be placed within the extensions folder, and the php_java.jar can be left right in the jdk.x.x.x folder.

Modifying the php.ini file

After you've installed the JDK, the next step is to modify the php.ini file. The first action you'll need to take is to add the following line to the extensions section:

extension=php_java.dll

Next, scroll down to the section titled [Java]. You'll see four configuration directives, namely java.class.path, java.home, java.library, and java.library.path. Modify these directives to read as seen below. I'll assume that you've installed PHP in the directory C:\php4. If you haven't please change the following to point to the correct directory path as necessary.

; This must point to the location of php_java.dll.
java.library.path = "C:\php4\extensions;"

; This points to the directory where your Java 
; classes will be stored.  You can designate multiple
; paths, each path separated by a semicolon.
; It must also include the location of php_java.jar
java.class.path = "C:\php4\extensions\jdk1.2.2\php_java.jar;"

; This points to the bin directory of the JDK.
java.home = "C:\jdk1.2.2\bin"

; This must point to the Java Virtual Machine (jvm.dll) file.
java.library = "C:\jdk1.2.2\jre\bin\classic\jvm.dll"
Once you've successfully installed the JDK and configured the PHP php.ini file, take a moment to test your configuration using the example shown in the next section, "Using Java's Predefined Library."

Using Java's predefined library

Once configured, you can begin using Java's predefined class libraries. In Listing 1, I make use of the java.lang.system library to display the total number of seconds since January 1, 1970.

Listing 1: Using Java's predefined java.lang.System library.

<?php

$systemInfo = new Java("java.lang.System");

print "Total seconds since January 1, 1970: 
".$systemInfo->currentTimeMillis();

?>

Since this Java class has already been compiled, there is no need for any other steps other than to instantiate the class from within the Java() command. Executing Listing 1, you should see output similar to the following:

Total seconds since January 1, 1970: 978463526830

While the precompiled libraries (Java calls them "packages") are certainly useful, chances are you will want to use custom libraries written by both other developers or yourself. I'll show you how this is accomplished in the next section, "Using Custom Libraries."

The following is an error that commonly arises when making the first attempts to integrate PHP and Java:

Warning: java.lang.ClassNotFoundException

There are three likely errors that could be the cause of this message:

Therefore, if you are receiving this error, take a moment to review each of the above possibilities as they pertain to your code.

Using custom libraries

Of course, chances are you will want to implement custom-written classes within your applications, rather than relying solely on those packages provided by the Java distribution. To illustrate how these third-party classes are used within a PHP application, I'll create a simple Java class that calculates sales tax based upon a price and taxation rate input by the user, shown in Listing 2. You'll need to compile salesTax.java using the Java compiler before you can use this class within the PHP script shown in Listing 3. I'll show you how this is accomplished in a bit. For the moment, just take some time to review Listing 2.

Listing 2: salesTax.java

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;

    }

}

Once you've saved this code within a file named salesTax.java, you'll need to compile it. This is accomplished by executing the following command:

%>javac salesTax.java

Assuming that you haven't introduced any errors into the code, a new, compiled file named salesTax.class will be created. This is the compiled code that will be called by PHP to perform the calculation based on the data input by the user via an HTML form. This form, along with the PHP code that calls salesTax.class, is shown in Listing 3 (salesTaxInterface.php).

Listing 3: salesTaxInterface.php

<?php

// Format the HTML form.
$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 :

   // Instantiate the SalesTax class.
   $salesTax = new Java("SalesTax");

   // Don't forget to typecast in order to
   // conform with the Java method specifications.
   $price = (double) $price;
   $tax = (double) $tax;

   print $salesTax->SalesTax($price, $tax);

endif;

?>

Troubleshooting

Chances are you will encounter various minor problems when you first attempt to integrate Java and PHP functionality, particularly if you are a relative newcomer to the Java programming environment. Even if the Java code compiles correctly, you may still encounter problems, largely due to differences found between the two languages. I'll outline two of these differences here:

Data types

As you may know, PHP is a loosely-typed language, which means it is rather lenient on the way variables are used. On the contrary, Java is a strongly-typed language, which means that its policies for handling variables and data types are rather stringent. To illustrate the problem this difference poses, take a moment to again review the code found in Listing 3. Notice that I had to typecast the $price and $tax variables before passing them to the SalesTax() method, because this method requires that both input parameters are of type "double." If this is not done, then input such as 24 for price would cause an error to occur.

Furthermore, if you are not adamant in ensuring the correct data types are passed to the Java methods, you may receive unexpected results, although it will not be outwardly apparent that an error has occurred. Therefore, be careful!

Error reporting

Errors occurring within a PHP script are reported in accordance with the level of error-reporting specified in the php.ini file. Because the Java code is called from within the PHP script, any errors that arise from the Java code are displayed as PHP errors. If you would like to prevent these errors from being displayed to the browser, simply prefix a @ symbol to the PHP command.

Conclusion

This article introduced you to what is in my opinion one of PHP's coolest new features, the Java extension. Using this extension opens up a whole new realm of possibilities for enhancing your existing applications, some of which I introduced in this article. Furthermore, I discussed several problems which may arise as a result of integrating these two languages, both on a general configuration level and on the level of inconsistencies between the languages.

Next time, I'll introduce another new and interesting extension, Shockwave. You'll be shocked at the cool presentations you can make with just a few lines of PHP code.

W.J. Gilmore has been developing PHP applications since 1997, and is frequently published on the subject within some of the Web's most popular development sites. He is the author of 'A Programmer's Introduction to PHP 4.0' (January 2001, Apress), and is the Assistant Editorial Director of Web and Open Source Technologies at Apress.


Return to the PHP DevCenter.

Copyright © 2009 O'Reilly Media, Inc.