home forums resources search newsjoinmembers: 6499
Hiveminds Network PHP Flash Java Ruby Windows Linux
php | Wed, 2008-06-25 10:54  tags: , ,

Update: The php/java bridge files needed to run this tutorial as it was created orginally can be downloaded from here( version 3.2.1) . The present version of the php java bridge does not support this windows version of the tutorial.

Here's how to team up two of the most popular and powerful platforms for web development together. With the php-java bridge you can build classes and jar files in Java and call them and use their methods in PHP. Use the quick and easy PHP language to bring Java muscle to your web pages.

In this tutorial I am using Windows 2000 Server, PHP 5.1.4 and php-java bridge 3.1.6. Windows is my operating system of choice but there is information on installing and using php-java bridge on Linux and Mac OS. You can find it under the resource link at the end of the article. I am going to assume that you have a bit of knowledge about both PHP and Java. You should know enough to get them installed and be able to do simple coding in both.

JDK

Download and install Java 5 JDK. You can use the Java 6 Beta if you like but the latest stable is jdk 1.5.0_09. I wanted to make sure my rusty Java skills were not further hindered by a beta software glitch. It's bad enough that everything I have learned in Java 2 and all my book samples bring up those nasty deprecated messages whenever I try to compile something.

Once you have installed the JDK you will need to adjust the PATHS to point to the Java installation and the set a CLASSPATH. Follow the next steps.

Create an AUTOEXEC.BAT file

  1. Click on START (lower left)
  2. Click on run
  3. Where is says "open" type in "command" and click OK.  This gets you to the DOS prompt.
  4. Type "cd c:\"
  5. Type "notepad autoexec.bat"  -- this will bring up the notepad editor.  In this editor type the following two lines:
    set PATH=%PATH%;C:\Program Files\Java\jdk1.5.0_09\bin;
    set CLASSPATH=.
  6. Exit notepad.

Wampserver

Wampserver is my choice of Apache2, MySQL and PHP. I find that it is easier and lighter weight than XAMPP. All too frequently I get emails about how to do things in XAMPP. The answer is, the same way as you would in Wampserver. My feeling is if XAMPP is your choice then you should take sometime to learn about it. There is just not enough difference between the two to make doing a seperate article necessary. They are both WAMP packages in the end.

The PHP-Java Bridge

This is the key to getting everything to work. The php-java bridge is a dll file. It is stable but does not seem to be documented very well. I have a feeling this will change soon but until then you need to know a few things to get it going. The first thing is that the files once downloaded and decompressed do not show. This threw me off for a while until I decided to test the functions. When I launched the test.bat file the rest of the installation files appeared.

So I copied the directory holding them over to the preset Apache htdocs directory for wampserver and surfed to the test.php that was showing. The result was a warning that I was using the wrong php-java.dll and php-java.jar file. These incorrect files were the ones that came with the installation ow Wampserver. The next step was to copy the correct files files from the php-java install directory over to the Wampserver Apache PHP directory where the PHP extensions were stored. Then I surfed to the test page again and was greeted by phpinfo screen and other information that could only come from PHP talking to Java. Very cool!

Java

From here things get easier and easier. The code below is your sample Java code that needs to be compiled into a Java class to be called from PHP. Take the code show below and place it in a text editor and save it as "hello.java" in a directory. Compiling is easy just start up the command prompt go to the directory holding the hello.java file and give the c:> javac hello.java command. This will create a hello.class file. You can leave it there and give the path to it when coding your PHP.

For those that don't know much Java yet here's some Hello World code with a little spice to it so it does not get boring.

//------------------------------------------------------------------ 
import java.util.*;
import java.text.*;
import java.math.*;

public class hello { 
public static void main(String[] args) { 
//do nothing - this will keep us from getting a compile error 
} 
public String SayHello() {
  Date today = new Date();
  return "Hello Geek here is the java date and time: " + today; 
}

public int SayNumber(){
  int mynum = 0;
    for(int i=1;i<=5;i++){
       mynum =+ (int)(Math.random()*100);
    }
    return mynum;
}
} //------------------------------------------------------------------

PHP

The PHP code here is simple and straight forward. It is not OOP. But you probably got enough of that while doing the Java code.

<?php

java_require
("F:\\wamp5\\www\\classes\\");
$obj = new Java("hello");
// Call the "sayHello()" method
$output $obj->SayHello();
echo 
$output.'  this text in PHP<br />'// Displays (so this comes from the class!)
// Call the "SayNumber()" method
$output $obj->SayNumber();
// Displays (so this comes from the class!)
echo $output.' is a lucky number'
//Because the JVM caches everything we want reset while playing with the code. Otherwise the
// a cached version of the same class file will be used rather than the new one
echo "<br />Resetting back-end to initial state\n";
// suppress the warning message from the use of reset.
@java_reset();

?>

That's it. Now browse to the PHP page and you should get the results shown below.

Make note of the @java_reset() function at the end of the PHP snippet. It is very important to remember to add this while testing. This is because the Java JVM caches the call to and the Java object. Without java_reset() when you update a class file you will get the previously cached one instead.

More code and tips on installation to Mac OSX and Linux OS can be found here at php.net. If you need support there is a mailing list at php-java-bridge-users@lists.sourceforge.net. Though there is little activity the core developers of the php-java bridge are there to help.

Conclusion

The php-java bridge is stable and should not be hard to talk a web hosting provider into installing if they have not done so already. While Java hosting is not as wide-spread as PHP with the recent changes made in the licensing this will change also. The best part of all is that this gives PHP programmers a good reason to learn Java and vice versa.

Related:


Happy Publishing!

php's picture
Pia Weathers - database systems engineer
 
a Visitor posted on: Wed, 2006-11-22 20:42.

thanks for the update...it's been a while but every year or so I fire up the latest php-java bridge and always it flakes out. seems that they may have finally got it reliable. maybe I'll resurrect an old project.

thanks.

a Visitor posted on: Thu, 2006-11-23 23:45.

I'm interesting about the life of java object loaded, can it stay alive after php request? or dead with php?

a Visitor posted on: Fri, 2006-11-24 05:43.

as far as i think it wud be dead just the php page execution ends as it normally happens with a php object!

a Visitor posted on: Wed, 2006-11-29 06:52.

The class loader is what is caching. It seems the class loader is different on each type of JVM. You can also write your own class loader. The programmers for php-java bridge use the GNU loader and provide a means for emptying the cache. If you use another type then you may have to find that loaders method for emptying the cache.

a Visitor posted on: Wed, 2006-11-29 15:55.

Shouldn't the java_reset() be called in the beginning of the script? Now, if the PHP script failes, the JVM will not reset.

Hiveminds posted on: Thu, 2006-11-30 11:38.

I don't think it will effect the outcome much. Although if set at the beginning reset() will try and clear the cache before the PHP code calls the loader and the cache is empty on the first run.

a Visitor - posted on: Wed, 2006-12-20 06:30.

The project team is pleased to announce a new and snazzy Web site for
the php/Java bridge project.

http://php-java-bridge.sourceforge.net/pjb/index.php

The new Web site features better organization of all of the work Jost
has compiled over the years and will include some new sections to
highlight examples of using the bridge, case studies from our user
community, and upcoming platform-specific installation guides.

We look forward to your suggestions and comments on the new site.

a Visitor posted on: Tue, 2007-02-27 07:00.

Get php running correctly for command line php only
and get java running too so you can compile. I used
jdk 1.5.0_11 and php 5.2.0

Download JavaBridge 4.0.1 and extract the JavaBridge.war

from the .war extract JavaBridge.jar to a folder
on your box.

in that folder do:
java -jar JavaBridge.jar SERVLET:9090

which starts up a server for you.

then use:

import java.util.*;

import java.text.*;

import java.math.*;

public class Hello {

public static void main(String[] args) {

int i; // Do nothing

}

public String SayHello () {

Date today = new Date();

return "Hello Geek, today is " + today;

}

public int SayNumber () {

int mynum = 0;

for (int i=1; i

mynum =+ (int)(Math.random()*100);

}

return mynum;

}

}

and compile to another folder. I used
C:\Documents and Settings\root

Then code a php file:

<?php

require_once("http://localhost:9090/JavaBridge/java/Java.inc");
try {
java_require("C:\\Documents and Settings\\root\\");
$obj = new Java("Hello");
$output $obj->SayHello();
echo 
java_values($output) . "\n";
$output $obj->SayNumber();
echo 
java_values($output) . "\n";
@
java_reset();
       } catch(
JavaException $ex) { 
   
$exStr java_cast($ex"string"); 
   echo 
"Exception occured; mixed trace: $exStr\n"
   
$trace = new java("java.io.ByteArrayOutputStream"); 
   
$ex->printStackTrace(new java("java.io.PrintStream"$trace)); 
   print 
"java stack trace: $trace\n"


?>

have fun.

b.t.w, the Tomcat server runs this ok too on the 8080
port (when you deploy the .war), but I wanted to try command line and pure the java server only.

It works w/o the dll stuff since there can be
problems between PHP and the dll versioning.

a Visitor posted on: Fri, 2007-06-08 04:09.

i hv follow every step u explain but still got this error :

#!/bin/env php Please permanently activate the extension. Loading java extension php_java.dll now...

Warning: dl() [function.dl]: Not supported in multithreaded Web servers - use extension=php_java.dll in your php.ini in C:\Program Files\xampp\htdocs\php-java-bridge\test.php on line 42
Please permanently activate the extension. Loading java extension java-x86-windows.dll now...

Warning: dl() [function.dl]: Not supported in multithreaded Web servers - use extension=java-x86-windows.dll in your php.ini in C:\Program Files\xampp\htdocs\php-java-bridge\test.php on line 42
Please permanently activate the extension. Loading java extension php_java.dll now... Error: Either the java extension is not installed or it was compiled against an older or newer php version. See the HTTP (IIS or Apache) server log for details.

hw can i solve this error?

help me

thanx

a Visitor posted on: Tue, 2007-10-23 13:15.

I don't understand because I'm unable to make java work on my windows XP installation with wamp server running. I tried all you said, and when I launch the test.php file from within the bridge directory, the result.html file says everything is working fine, BUT when I do a phpinfo from within my www of my wamp installation, I still has no java line at all in the infos provided. Dunno what's wrong...




Bitrix Site manager - fast to create, easy to manage CMS Comparison Matrix
Put Your Site Here Developer Links
Joomla! Adobe Flex Web Developers Silverlight Adobe Flex Wordpress Drupal Content Management Systems Adobe Flex
 

Newsletter

Get updates on Hiveminds services, articles and downloads by signing up for the newsletter.

Editor's choice

Some of the better articles, stories and tutorials found at Hiveminds.

Find more

Find more of Hiveminds articles, stories, tutorials and user comments by searching.




Picked links

Hand picked websites and articles from around the web that provide quality reading.