# What is the PHP/Java Bridge?

The PHP/Java Bridge is a PHP module, `java.so`, `php_java.dll`, with an associated backend, `JavaBridge.jar`, `JavaBridge.war` or `MonoBridge.exe`, which connects the PHP object system with Java or a ECMA 335 virtual machine. It fully implements JSR 223 and can be used to access CLR (e.g. VB.NET, C#) or Java (e.g. Java, KAWA, JRuby) based applications from PHP scripts. The PHP/Java Bridge communicates with the VM through local sockets using an efficient communication protocol. Each request-handling PHP process of a multi-process HTTP server communicates with a corresponding thread spawned by the VM.

Requests from more than one HTTP server may either be routed to an application server running the PHP/Java Bridge or each HTTP server may own a PHP/Java Bridge and communicate with a J2EE java application server by exchanging java value objects; the necessary client-stub classes (ejb client .jar) can be loaded at run-time.

ECMA 335 based classes can be accessed if at least one backend is running inside a ECMA complient VM, for example Novell's MONO or Microsoft's .NET. Special features such as varargs, reflection or assembly loading are also supported.

When the backend is running in a J2EE environment, session sharing between PHP and JSP is always possible. Clustering and load balancing is available if the J2EE environment supports these features.

Unlike previous attempts (the ext/java or the JSR223 sample implementation) the PHP/Java Bridge does not use the java native interface ("JNI"). Php instances are allocated from the HTTP (Apache/IIS) pool, instances of java/j2ee components are allocated from the backend. The allocated instances communicate using a "continuation passing style", see `java_closure()` below. In case a php instance crashes, it will not take down the java application server or servlet engine.

Since PHP/Java Bridge version 3.0 it is also possible to use java as an "execution environment" for php scripts, java code can allocate and invoke php scripts from an external or internal pool. The script instances can be allocated from an external HTTP (e.g.: Apache/IIS) pool, from a internal php FastCGI pool or directly using the php CGI interface. Java 6 or an external `javax.script` package is required to use this functionality, please see the `javax.script` package for details.

# Why use PHP/Java Bridge?

PHP components are essentially transient. For complex applications is usually necessary to introduce "middleware" components such as (enterprise-) "java beans" or enterprise applications which provide caching, connection pooling or the "business logic" for the pages generated by the PHP components. Parsing XML files for example is an expensive task and it might be necessary to cache the generated graph. Establishing connections to databases is an expensive operation so that it might be necessary to re-use used connections. The standard PHP XML or DB abstractions are useless in this area because they cannot rely on a middle tier to do caching or db connection pooling.

Even for trivial tasks it might be necessary to use a java class or java library. For example it might be necessary to generate Word, Excel or PDF documents without tying the application to a specific system platform.

PHP, the PHP/Java Bridge and the php files can be packaged within a standard J2EE archive, customers can easily deploy it into a J2EE application server or servlet engine. They don't have to install PHP and they usually cannot tell the difference whether the pages are generated by PHP, JSP or servlets. Since the bridge allows session sharing between PHP and the J2EE components, developers can migrate their JSP based solutions to PHP step by step.

PHP and the PHP/Java Bridge might also be interesting for java developers. There are a number of technologies based on the JSP template system such as jakarta Struts and its successor Java Server Faces. JSP and custom taglibs have problems on their own, combining them to create an object-based web framework exposes these problems; the JSP page is parsed from the top to the bottom and the defined "components" render and contribute to the object graph in one pass. Even the JSF originators acknowledge that this system is seriously flawed and recommend a system like tapestry or facelets which define the components in java classes and bind them via ID's in the XML or HTML template. Since PHP/Java Bridge version 3.0 it is possible to embed php scripts or php methods into the JSF framework, so that UI developers can concentrate on developing HTML templates while web developers can create a prototype using php code and use the existing framework from their code.

The bridge adds the following primitives to PHP. The type mappings are shown in table 1.

- `new Java("CLASSNAME")`: References and instanciates the class CLASSNAME. After script execution the referenced classes may be garbage collected. Example:

  > `<?php
  > header("Content-type: application/x-excel");
  > header("Content-Disposition: attachment; filename=downloaded.xls");
  > java_require("http://php-java-bridge.sf.net/poi.jar");
  > // create a 200x200 excel sheet and return it to the client
  > $workbook = new java("org.apache.poi.hssf.usermodel.HSSFWorkbook");
  > $sheet = $workbook->createSheet("new sheet");
  > $style = $workbook->createCellStyle();
  > // access the inner class AQUA within HSSFColor, note the $ syntax.
  > $Aqua = new JavaClass('org.apache.poi.hssf.util.HSSFColor$AQUA');
  > $style->setFillBackgroundColor($Aqua->index);
  > $style->setFillPattern($style->BIG_SPOTS);
  > for($y=0; $y<200; $y++) {
  > $row = $sheet->createRow($y);
  > for($x=0; $x<200; $x++) {
  > $cell = $row->createCell($x);
  > $cell->setCellValue("This is cell $x . $y");
  > $cell->setCellStyle($style);
  > }
  > }
  > // create and return the excel sheet to the client
  > $memoryStream = new java ("java.io.ByteArrayOutputStream");
  > $workbook->write($memoryStream);
  > $memoryStream->close();
  > echo $memoryStream->toByteArray();
  > ?>
  > `

- `new JavaClass("CLASSNAME")`: References the class CLASSNAME without creating an instance. The object returned is the class object itself, not an object of the class. After script execution the referenced classes may be garbage collected. Example:

  > `$Object = new JavaClass("java.lang.Object");
  > $obj = $Object->newInstance();
  > $Thread = new JavaClass("java.lang.Thread");
  > $Thread->sleep(10);
  > `

- `java_require("JAR1;JAR2")`: Makes additional libraries available to the current script. JAR can either be a "http:", "ftp:", "file:" or a "jar:" location. On "Security Enhanced Linux" (please see the README) the location must be tagged with a lib_t security context. Example:

  > `$file=new java("java.io.File", "WEB_INF/web.xml");
  > java_require("xerces.jar;jdom.jar");
  > $builder = new java("org.jdom.input.SAXBuilder");
  > $doc = $builder->build($file);
  > $root = $doc->getRootElement();
  > $servlets = $root->getChildren("servlet");
  > echo "this file has " . $servlets->size() . " servlets\n";
  > `

- `java_context()`: Makes the `javax.script.ScriptContext` available to the current script. Available since PHP/Java Bridge version 3.0. Example:

  > `<?php
  > function toString() {
  > $testVal = java_context()->getAttribute("testKey");
  > return "Hello Java from Simple.php script: $testVal.";
  > }
  > ?>
  > public class MyServlet extends php.java.script.PhpScriptServlet {
  > public void service (ServletRequest req, ServletResponse res) throws ServletException {
  > ScriptEngine engine = getEngine(req);
  > ScriptContext ctx = getContext(req, res);
  > ctx.setAttribute("testKey", "testVal", ScriptContext.ENGINE_SCOPE);
  > // allocate a php instance from the HTTP (Apache/IIS) pool ...
  > Reader reader = new URLReader(new URL("http://localhost:80/Simple.php"));
  > engine.eval(reader, ctx);
  > // and invoke the above toString() function.
  > Object phpTopLevelEnvironment = ((Invocable)engine).getInterface(null, null);
  > String s = phpTopLevelEnvironment.toString();
  > res.getWriter().write(s);
  > // release the allocated php continuation (i.e.
  > // release the request-handling HTTP process/thread)
  > releaseEngine();
  > ctx.remove();
  > }
  > }
  > `

- `java_closure(ENVIRONMENT, MAP, TYPE)`: Makes it possible to call PHP code from java. It closes over the PHP environment and packages it up as a java class. If the ENVIRONMENT is missing, the current environment is used. If MAP is missing, the PHP procedures must have the same name as the required procedures. If TYPE is missing, the generated class is "generic", i.e. the interface it implements is determined when the closure is applied. Example which uses PHP and Mono:

  > `class GtkDemo {
  > var $Application;
  > function GtkDemo() {
  > mono_require("gtk-sharp"); // link the gtk-sharp library
  > }
  > function delete($sender, $e) {
  > echo "delete called\n";
  > $this->Application->Quit();
  > }
  > function clicked($sender, $e) {
  > echo "clicked\n";
  > }
  > function init() {
  > $this->Application = $Application = new Mono("Gtk.Application");
  > $Application->Init();
  > $win = new Mono("Gtk.Window", "Hello");
  > $win->add_DeleteEvent (
  > new Mono(
  > "GtkSharp.DeleteEventHandler",
  > mono_closure($this, "delete")));
  > $btn = new Mono("Gtk.Button", "Click Me");
  > $btn->add_Clicked(
  > new Mono(
  > "System.EventHandler",
  > mono_closure($this, "clicked")));
  > $win->Add($btn);
  > $win->ShowAll();
  > }
  > function run() {
  > $this->init();
  > $this->Application->Run();
  > }
  > }
  > <br>
  > $demo = new GtkDemo();
  > $demo->run();
  > `

  The java_closure can also be used to emulate try/catch functionality in PHP4. The following example calls the "strategy.call()" method which catches the exception raised in the php method m1() and calls the php method e($ex) with the raised exception as an argument:

  > `interface IStrategy {
  > public void m1();
  > public int m2();
  > public int e(Exception ex);
  > public class Strategy {
  > public int call(IStrategy phpClosure) {
  > try {
  > phpClosure.m1();
  > return phpClosure.m2();
  > } catch (Exception ex) {
  > return phpClosure.e(ex);
  > }
  > }
  > }
  > }
  > <?php
  > function m1 () {
  > $str=new java("java.lang.String", null); //raises NP exception
  > if(java_last_exception_get()) return;
  > echo "in m1"; //never reached
  > }
  > function m2 () {
  > echo "in m2";
  > return 1;
  > }
  > function e($ex) {
  > echo "exception raised on php level: $ex";
  > return 2;
  > }
  > $s = new Java('IStrategy$Strategy');
  > $result = $s->call(java_closure());
  > echo $result; // should display 2
  > ?>
  > `

- `$session=java_session()`: Creates or retrieves a session context. When the backend is running in a J2EE environment, the session is taken from the request object, otherwise it is taken from PHP. Please see the ISession interface documentation for details.

  > `$session = java_session();
  > $servletRequest = $session->getServletRequest();
  > $servletRequest->setAttribute(...);
  > ...
  > `

- `$session=java_session(SESSIONNAME)`: Creates or retrieves the session `SESSIONNAME`. This primitive uses a "private" session store with the name SESSIONNAME. Please see the ISession interface documentation for details. For java values `$_SESSION['var']=val` is syntactic shugar for `java_session(session_id())->put('var', val)`.

  > `$session=java_session("testSession");
  > if($session->isNew()) {
  > echo "new session\n";
  > $session->put("a", 1);
  > $session->put("b", 5);
  > } else {
  > echo "cont session\n";
  > }
  > $session->put("a", $session->get("a")+1);
  > $session->put("b", $session->get("b")-1);
  > $val=$session->get("a");
  > echo "session var: $val\n";
  > if($session->get("b")==0) $session->destroy();
  > `

  The `java_session` primitive is meant for values which must survive the current script. If you want to cache data which is expensive to create, bind the data to a class. Example:

  > `// Compile this class, create cache.jar and copy it to /usr/share/java
  > public class Cache {
  > public static Cache instance = makeInstance();
  > }
  > <?php
  > java_require("cache.jar");
  > $Cache = new JavaClass("Cache");
  > $instance=$Cache->instance; //instance will stay in the VM until the VM runs short of memory
  > ?>
  > `

- `JavaException`: A java exception class. Available in PHP 5 and above only. Example:

  > `try {
  > new java("java.lang.String", null);
  > } catch(JavaException $ex) {
  > $trace = new java("java.io.ByteArrayOutputStream");
  > $ex->printStackTrace(new java("java.io.PrintStream", $trace));
  > print "java stack trace: $trace\n";
  > }
  > `

- `foreach(COLLECTION)`: It is possible to iterate over values of java classes that implement java.util.Collection or java.util.Map. Available in PHP 5 and above only. Example:

  > `$conversion = new java("java.util.Properties");
  > $conversion->put("long", "java.lang.Byte java.lang.Short java.lang.Integer");
  > $conversion->put("boolean", "java.lang.Boolean");
  > foreach ($conversion as $key=>$value)
  > echo "$key => $value\n";
  > `

- `[index]`: It is possible to access elements of java arrays or elements of java classes that implement the java.util.Map interface. Available in PHP 5 and above only. Example:

  > `$Array = new JavaClass("java.lang.reflect.Array");
  > $String = new JavaClass("java.lang.String");
  > $entries = $Array->newInstance($String, 3);
  > $entries[0] ="Jakob der Lügner, Jurek Becker 1937--1997";
  > $entries[1] ="Mutmassungen über Jakob, Uwe Johnson, 1934--1984";
  > $entries[2] ="Die Blechtrommel, Günter Grass, 1927--";
  > for ($i = 0; $i < $Array->getLength($entries); $i++) {
  > echo "$i: " . $entries[$i] ."\n";
  > }
  > `

- `java_instanceof(JAVA_OBJ, JAVA_CLASS)`: Tests if JAVA_OBJ is an instance of JAVA_CLASS. Example:

  > `$Collection=new JavaClass("java.util.Collection");
  > $list = new java("java.util.ArrayList");
  > $list->add(0);
  > $list->add(null);
  > $list->add(new java("java.lang.Object"));
  > $list->add(new java("java.util.ArrayList"));
  > foreach ($list as $value) {
  > if($value instanceof java && java_instanceof($value, $Collection))
  > /* iterate through nested ArrayList */
  > else
  > echo "$value\n";
  > }
  > `

- `java_last_exception_get()`: Returns the last exception instance or null. Since PHP 5 you can use `try/catch` instead.
- `java_last_exception_clear()`: Clears the error condition. Since PHP 5 you can use `try/catch` instead.

Table 1. Type Mappings

PHP | Java | Description | Example
--- | --- | --- | ---
object | java.lang.Object | An opaque object handle. However, we guarantee that the first handle always starts with 1 and that the next handle is n+1 for all n < 1024 (useful if you work with the raw XML protocol, see the python and scheme examples). | $buf=new java("java.io.ByteArrayOutputStream"); $outbuf=new java("java.io.PrintStream", $buf);
null | null | NULL value | $outbuf->println(null);
exact number | long | 64 bit integer | $outbuf->println(100);
boolean | boolean | boolean value | $outbuf->println(true);
inexact number | double | IEEE floating point | $outbuf->println(3.14);
string | byte[] | binary data, unconverted | $bytes=$buf->toByteArray();
string | java.lang.String | An UTF-8 encoded string. Since PHP does not support unicode, all java.lang.String values are auto-converted into a byte[] (see above) using UTF-8 encoding. The encoding can be changed with the `java_set_file_encoding()` primitive. | $string=$buf->toString();

array (as array)

java.util.Collection or T[]

PHP4 sends and receives arrays as values. PHP5 sends arrays as values and receives object handles which implement the new iterator and array interface.

// pass a Collection to Vector
$ar=array(1, 2, 3);
$v=new java("java.util.Vector", $ar);
echo $v->capacity();
// pass T[] to asList()
$A=new JavaClass("java.util.Arrays");
$lst=$A->asList($ar);
echo $lst->size();

array (as hash) | java.util.Map | PHP4 sends and receives hashtables as values. PHP5 sends hashtables as values and receives object handles which implement the new iterator interface. | $h=array("k"=>"v", "k2"=>"v2"); $m=new java("java.util.HashMap",$h); echo $m->size();
JavaException | java.lang.Exception | A wrapped exception class. The original exception can be retrieved with $exception->getCause(); | ... catch(JavaException $ex) { echo $ex->getCause(); }

There is one example provided: test.php. You can either invoke the test.php by typing ./test.php or copy the example into the document root of you web-server and evaluate the file using the browser.

The PHP/Java bridge is a replacement for the experimental ext/java bridge shipped with PHP 4. It is not possible to run the build-in bridge and the PHP/Java bridge at the same time.

The module has been tested on a Mandrake Linux System (Version 9.2), on RedHat Enterprise 3, RedHat Fedora Core 1..4, FreeBSD 5.3, Solaris 9 (Sparc, 64 bit JVM) and Windows with RedHat Cygwin, but it should run on all Unix-like operating systems.

Custom java libraries (.jar files) can be stored in the following locations:

1. Somewhere on a HTTP or FTP server, see PHP function java_require. On Security Enhanced Linux `.jar` files can only be loaded from locations which are tagged with the lib_t security context.
2. In the sub-directory "lib" of the PHP extension directory, if it exists and is accessible when the JVM starts the bridge. This is usually "`php-config --extension-dir`/lib". On Security Enhanced Linux this directory is tagged with the lib_t security context.
3. In the `/usr/share/java/` directory, if it exists and is accessible when the JVM starts the bridge. On Security Enhanced Linux this directory is tagged with the lib_t security context.

The PHP/Java Bridge can operate in 4 different modes:

1. Invoked from the dl() function. In this mode the bridge starts when the HTTP server receives a client request and terminates after the response is written. This is very slow because it starts a new Java VM for each request. But it does not require any administrative privileges.
2. Permanently activated in the global php.ini file with an internal java process running in the HTTP server domain. In this mode the bridge starts when the HTTP server starts and terminates when the HTTP server terminates. Recommended during development. Please see web server installation below.
3. Permanently activated in the global php.ini file with an external java process. Recommended for production systems. This mode is used by the RPM package available for RedHat Enterprise Linux. In this mode the bridge starts and stops as a system service.
4. Permanently activated in the global php.ini file with an external application server or servlet engine. PHP be can run as a CGI sub-component within a pure java application server or be installed as a Apache/IIS module.

Furthermore the PHP/Java Bridge can be:

- Compiled into PHP. This is not recommended because it requires a compilation of the entire PHP library. If you want to do this, please read the README file. This should only be necessary if the OS does not support shared libraries.
- Compiled with the GNU Java library. You can either start GNU Java as a separate process (just like a "real" Java VM) or compile everything into a PHP binary. This should only be necessary if there is no official JRE available for the OS or one doesn't want to ship a JRE with the product.
- Compiled with Novell's MONO (a ".NET" clone). This is available as a separate download.

# Installation instructions

If you have a RedHat Linux system (RedHat Enterprise or Fedora), you can download the 32bit RPM and type `rpm -i php-java-bridge-v.x.y-z-i386.rpm` to install it (if you run a 64bit system and a 64bit JVM you need to install the 64bit RPM instead). For other operating systems please follow the instructions below (on Security Enhanced Linux please use the RPM or please read the README before installation).

- Make sure you have java version 1.4 or higher, gcc 3.2 or higher, apache 1.3 or higher, autoconf 2.57 or higher, libtool 1.4.3 or higher, automake 1.6.3 or higher, GNU make and php 4.3.2 or higher installed. You can check the version numbers with the commands `java -version`, `gcc --version`, `apachectl -version`, `libtool --version`, `automake --version`, `make null --version`, `autoconf --version` and `php-config --version`. Make sure that the java version you use matches the kernel version. RedHat NPTL kernels or kernel >= 2.6 require either an IBMJava2, Sun Java >= 1.4.2_02. For RedHat Enterprise Linux an appropriate java RPM is available on CD#9. GNU Java is currently only supported on Linux and Solaris if you use the GCC 3.3.x or the upcoming GCC 4.x releases.

- Download the source code of the bridge from http://www.sourceforge.net/projects/php-java-bridge

- Extract the file with the command: `cat php-java-bridge_v.x.y.tar.bz2 | bunzip2 | tar xf -`

- In the directory php-java-bridge-v.x.y build the module for a 32 bit JVM (if you run a 64 Bit JVM, use the `-m64` flag instead):
  `phpize && ./configure --disable-servlet --with-java=/opt/IBMJava2-14 && make CFLAGS="-m32"`

- Then install the module as root. Type:
  `su -c 'make install'
  <enter password>`

- The PHP/Java Bridge can be run as a sub-component of the web server; add the following lines to the `php.ini`. Or add a file `java.ini` to the directory that contains the php module descriptions (usually `/etc/php.d/`) with the following content:
  `extension = java.so
  [java]`

- Restart the apache service with the command: `apachectl restart`

- You can now test the web installation. Copy the test.php file to the document root (usually /var/www/html) and invoke the file with your browser. You should see that the bridge module is activated and running. The bridge starts or re-starts automatically whenever you start or re-start the web-server.

- In a production environment it is recommended to separate the java VM and the HTTP process by setting the communication channel. The `java.socketname` should be set to the name of the socket, it will be created if it doesn't exist. The `.ini` file should contain:
  `extension = java.so
  [java]
  java.socketname="/var/run/.php-java-bridge_socket"`
  The advantage of this mode is that the java VM no longer depends on the web server and can be examined and re-started independently. The download file contains a script, `php-java-bridge.service`, which can be used to start/stop the PHP/Java Bridge as system service. All available `.ini` options are listed in table 2.

- In a production environment which requires load balancing and failover or session sharing between PHP, JSP and Servlets it is recommended deploy the backend into a servlet engine or an application server; tomcat 5 for example. Disable the `java.socketname`, either a) enable the `java.hosts` and `java.servlet` options or b), if you don't have Apache or IIS, install PHP as a CGI/FastCGI binary so that your application server can find it and start the application server. The `.ini` file should contain:
  `extension = java.so
  [java]
  java.hosts="127.0.0.1:8080"
  java.servlet="/JavaBridge/PhpJavaServlet.php"`

Table 2. `.ini` options

Name | Default | Description | Example
--- | --- | --- | ---
java.java_home | compile time option. | The java installation directory. | java.java_home="/opt/jdk1.5"
java.java | compile time option. | The java executable. | java.java="/opt/jdk1.5/jre/bin/java"
java.socketname | /var/run/.php-java-bridge_socket | The name of the communication channel for the local backend. Must be an integer on windows. | java.socketname="9167"
java.log_level | 1 | The log level from 0 (log off) to 4 (log debug). | java.log_level="3"
java.log_file | /var/log/php-java-bridge.log | The log file for the local PHP/Java Bridge backend. | java.log_file="/tmp/php-java-bridge.log"
java.hosts | <none> | Additional bridge hosts which are used when the local backend is not available. | java.hosts="127.0.0.1:9168;127.0.0.1:9169"
java.servlet | Off | The communication protocol. If set to "On" or to "/yourContext/YourServlet", the bridge uses HTTP to communicate with the `java.hosts` backends. | `;; Make sure that this option is only set ;; if your backend is deployed in a ;; servlet engine or application server.` java.servlet="/JavaBridge/PhpJavaServlet.php"
java.classpath | compile time option. | The java classpath. Please do not change the default value | java.classpath="/tmp/myJavaBridge.jar:/tmp/myCasses/"
java.libpath | compile time option. | The directory which contains the `natcJavaBridge.so` used for local ("unix domain") sockets. Please do not change the default value. | java.libpath="/tmp/"

For further information please read the README, INSTALL and INSTALL.WINDOWS documents contained in the download files.

# Related

- A tutorial how to use the predecessor "ext/java".
- A commercial bridge which uses the same technology as the PHP/Java Bridge.
- Calling Enterprise Java Beans from PHP/SOAP.
- Calling Enterprise Java Beans from the PHP/Java Bridge.