The PHP Java Extension

Combining PHP with java

New Articles

JSP File Upload Progress bar.

The case of the missing errors.

Out of the Java Sandbox.

There is so much information in compiling and using the java extension for PHP it's qutie easy to become overwhelmed. In actual fact installation of the extension is quite easy. Here is a short and sweet guide.

Download and install the J2SDK

Binaries are available for almost any platform. At the time of writing, the most stable version is 1.4.2 and this is what you should obtain. If you have heard stories about using the 1.3.x or 1.2.x version because they are more widespread, forget them.

In my machine I installed the sdk on /opt/java/j2sdk1.4.2. You can install it anywhere you like but the rest of the article assumes this is the location. next you have to create the JAVA_HOME enviorenment variable. Add the following line to your .bash_profile or your /etc/profile

JAVA_HOME=/opt/java/j2sdk1.4.2
export JAVA_HOME
you may also want to add /opt/java/j2sdk1.4.2/bin to your path.

Compile the extension

You need to be familiar with building software from it's sources on linux systems and you need to be familiar with compiling PHP in particular.

Move into the etc/java folder in your source tree and execute

phpize
./configure
make
make install

Alternatively take a look at the config.status file to find your last settings for the ./configure command, add --with-java and go through the 'usual' php configuration and installation processs

Change the php.ini settings

The section of the php.ini file that pertains to the java extension looks like this

[Java]
java.class.path =/usr/lib/php4/php_java.jar
java.home = /opt/java/j2sdk1.4.2/
java.library = /opt/java/j2sdk1.4.2/jre/lib/i386/server/libjvm.so 
java.library.path = /usr/lib/php4/
extension_dir=/usr/lib/php4/
extension=java.so

Create the symlink

This is the most crucial step of the installation process. Find out where your libphp_java.so file has been installed (and make sure it's at the right location, in some cases I have seen extension shared objects been copied to all sorts of wierd places). Now you need to create a symbolic link as follows

ln -s java.so libphp_java.so

This piece of information was given by a person I only know by his email address [phpnet AT devnull DOT org DOT uk] in the php manual comments section. It's the key

Restart apache

After you have done all the above steps restart apache and load up a page that calls the phpinfo() function. You should see a new section labeled java among the results and it should match the settings you made in the ini file.

extract from the phpinfo.php()

Test your setup

In the ext/java folder in your source tree you will see sample sample scripts that make use of the PHP java extension. Move them to your htdocs and load up the page in your browser. You should see it start up.

Copyright © Raditha Dissanayake 2013