# What is the PHP/Java Bridge?

The PHP/Java Bridge is an optimized, XML-based network protocol which can be used to connect a native script engine with a Java or ECMA 335 virtual machine. It is more than 50 times faster than local RPC via SOAP, uses less resources on the web-server side and it is faster and more reliable than a communication via the Java Native Interface.

The php java extension uses this protocol to connect running PHP instances with already running Java or .NET back-ends. The communication works in both directions, the JSR 223 interface can be used to connect to a running PHP server (Apache/IIS, FastCGI, ...) so that Java components can call PHP instances and PHP scripts can invoke CLR (e.g. VB.NET, C#, COM) or Java (e.g. Java, KAWA, JRuby) based applications or transfer control back to the environment where the request came from. The bridge can be set up to automatically start the PHP front-end or the Java/.NET back-end, if needed.

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 back-end is running inside a ECMA compliant VM, for example Novell's MONO or Microsoft's .NET. Special features such as varargs, reflection or assembly loading are also supported.

When the back-end 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.

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 back-end. The allocated instances communicate using a "continuation passing style", see `java_closure()` and the invocable interface. In case a PHP instance crashes, it will not take down the java application server or servlet engine.

# Motivation

## J2EE as a standard framework for PHP scripts

All PHP components are essentially transient. For complex applications it 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.

## Platform independence

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.

## A standard distribution format

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.

## Migration from JSP to PHP

PHP and the PHP/Java Bridge might also be interesting for java developers. Although JSP is still used by frameworks such as jakarta Struts and its successor Java Server Faces, JSP is not and probably never will be a sucessful technology. The main problem with JSP is that it requires a development tool at run-time, a "compiler", which makes deployment difficult and may generate error messages which are very difficult to understand, because they refer to an intermediate representation which has nothing to do with the original JSP file. For example if the configuration changes, it may happen that users are confronted with compiler error codes or run-time messages like "NullPointerException in __jsp" instead of proper error messages from the program. Since PHP/Java Bridge version 3.0 it is possible to embed php scripts into the JSF framework, so that UI developers can concentrate on developing HTML or XML templates while web developers can create prototypes using PHP code and use the existing framework from their code.

# Overview

The PHP/Java Bridge consists of a large set of auto-generated PHP classes and an extension module for PHP versions >= 4.3.2. When the bridge has been compiled without java, no Java or Mono back-end's are necessary; popular Java libraries such as `lucene.jar` or `itext.jar` can be interpreted by the bridge code without using a Java SDK or Java JRE.

When the bridge has been compiled with Java, three back-ends are available: a "standalone back-end" called `JavaBridge.jar`, a J2EE back-end and Servlet SAPI `JavaBridge.war` and a Mono back-end called `MonoBridge.exe`.

To access Java libraries from PHP the following is necessary:

1. the extension module `java.so`/`php_java.dll` and the `JavaBridge.jar` should be installed in the PHP `extension_dir` directory,
2. the Java libraries should have been tranlated into PHP code and they should be installed into the PHP `include_path` directory. For example the following command translates the Java library `lucene.jar` into PHP classes and installs them into the `/usr/share/pear/lucene` directory:

   > `java -jar JavaBridge.jar --snarf /usr/share/pear lucene.jar`

The Java libraries can be accessed by including the PHP classes once. PHP code can call all public Java methods or procedures and examine all public fields. All public PHP procedures can be called from within Java, all PHP classes may implement Java interfaces and may be passed to Java procedures or methods. Example:

> `<?php
> require_once("org_apache_lucene_search_IndexSearcher.php");
> require_once("org_apache_lucene_search_PhraseQuery.php");
> require_once("org_apache_lucene_index_Term.php");
> $searcher = new org_apache_lucene_search_IndexSearcher(getcwd());
> $term = new org_apache_lucene_index_Term("name", "test.php");
> $phrase = new org_apache_lucene_search_PhraseQuery();
> phrase->add($term);
> $hits = $searcher->search($phrase);
> $iter = $hits->iterator();
> while($iter->hasNext()) {
> $next = $iter->next();
> $name = $next->get("name");
> echo "found name: $name\n";
> }
> ?>`

Java knowledge is not necessary and it is neither necessary nor recommended to write custom- or glue logic in the Java programming language.

The following sections describe the low-level Java interface which can be used to create dynamic PHP proxies or PHP/Java Bridge bindings for other languages such as Perl or Python.

# Description

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

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

  > `<?php
  > $v = new Java("java.util.Vector");
  > $v->add($buf=new Java("java.lang.StringBuffer"));
  > $buf->append("100");
  > echo (int)($v->elementAt(0)->toString()) + 2;
  > ?>
  > `

- `new JavaClass("CLASSNAME")`: References the class CLASSNAME without creating an instance. The returned object 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:" or a default location. On "Security Enhanced Linux" (please see the README) the location must be tagged with a lib_t security context. Example:
  `// load scheme interpreter
  // try to load it from /usr/share/java/ or from sourceforge.net
  try { java_require("kawa.jar"); } catch (JavaException $e) {/*ignore*/}
  java_require("http://php-java-bridge.sourceforge.net/kawa.jar");
  $n=100;
  $System = new JavaClass("java.lang.System");
  $t1 = $System->currentTimeMillis();
  $code="(letrec ((f (lambda(v) (if (= v 0) 1 (* (f (- v 1)) v))))) (f $n))";
  $scheme = new java("kawa.standard.Scheme");
  $res=(float)$scheme->eval($code);
  echo "${n}! => $res\n";
  $delta = $System->currentTimeMillis() - $t1;
  echo "Evaluated in $delta ms.\n";
  `
- `java_context()`: Makes the `javax.script.ScriptContext` available to the current script. All implicit web objects (session, servlet context, etc.) are available from the context, when the back-end is running in a servlet engine or application server. The following example uses the jdk1.6 `jrunscript` to eval PHP statements interactively:
  `/opt/jdk1.6/bin/jrunscript -l php-intractive
  php-interactive> echo java_context()->getAttribute("javax.script.name");
  => STDIN
  `
- `java_values(JAVA_OBJECT)`: Fetches the values for `JAVA_OBJECT`, if possible. Examples:

  > `$str = new java("java.lang.String", "hello"); echo $str;
  > => [o(String):"hello"]
  > // fetch the php string from the java string
  > echo (java_values($str));
  > => hello
  > // fetch the values of the java char array
  > print_r (java_values($str->toCharArray()));
  > => array('h', 'e', 'l', 'l', 'o')
  > // no php type exists for java.lang.Object
  > print (java_values(new java("java.lang.Object")));
  > => [o(Object):"java.lang.Object@4a85fc"]`

- `java_begin_document()` and `java_end_document()`: Enables/disables XML stream mode. In XML stream mode the PHP/Java Bridge XML statements are sent in one XML stream. Compared with SOAP, which usually creates the entire XML document before sending it, this mode uses much less resources on the web-server side. Raised server-side exceptions are reported when `java_end_document()` is invoked. Example:

  > `// send the following XML statements in one stream
  > java_begin_document();
  > for ($x = 0; $x < $dx; $x++) {
  > $row = $sheet->createRow($x);
  > for ($y = 0; $y < $dy; $y++) {
  > $cell = $row->createCell($y);
  > $cell->setCellValue("$x . $y");
  > $cell->setCellStyle($style);
  > }
  > }
  > java_end_document(); // back to synchronous mode
  > `

- `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:

  > `<?php
  > function toString() { return "hello" ; }
  > echo (string)java_closure();
  > ?>
  > => hello`

- `$session=java_session()`: Creates or retrieves a session context. When the back-end 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. The `java_session()` must be called before the response headers have been sent and it should be called as the first statement within a PHP script.

  > `$session = java_session();<Mr> $servletRequest = $session->getHttpServletRequest();
  > $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 sugar 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 (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 | integer (default) or long, depending on the flag java.ext_java_compatibility. | 64 bit data on protocol level, coerced to 32bit int/Integer or 64bit long/Long | $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 hash-tables as values. PHP5 sends hash-tables 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 your web-server and evaluate the file using the browser.

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 5 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 back-end (Java or .NET 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 back-end 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 Red Hat 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 or FastCGI sub-component within a pure java application server or be installed as a Apache/IIS module.
5. As a script extension within a pure java application (requires java >= 1.6).

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.
- Configured and compiled to run without java. The GNU gcc 4 compiler library gcj can used to interpret java libraries. Thus it is possible to use popular java libraries such as Apache's lucene or Lowagi's itext directly from PHP, without the need to install a java VM.
- Compiled with Novell's MONO (a ".NET" clone). This is available as a separate download.

# Installation instructions

If you have a Unix, Windows or Linux system, download either the binary or the source and install it.

## Installation on Linux

Open a command shell and type the following commands:

### Public key

All binary files are digitally signed. Before you install the RPM binaries you should install the public key, so that the integrity can be checked. If you haven't installed the key, type:

> `rpm --import RPM-GPG-KEY`

### RPM binaries

Either install the bridge and standalone back-end

> `rpm -i jdk-1_5_0-linux-i586.rpm
> rpm -i php-java-bridge-x.y.z-1-i386.rpm
> rpm -i php-java-bridge-standalone-x.y.z-1-i386.rpm
> `

or the tomcat back-end

> `rpm -i tomcat5-5.0.30-5jpp_6fc.i386.rpm
> rpm -i php-java-bridge-tomcat-x.y.z-1.i386.rpm`

or the development files for JDK 1.6

> `rpm -i jdk-6-linux-i586.rpm
> rpm -i rpm -i php-java-bridge-devel-x.y.z-1.i386.rpm
> `

If you run a 64bit system and a 64bit JVM, you need to build a 64bit RPM using the command:

> `rpmbuild --rebuild php-java-bridge-x.y.z-1.src.rpm
> `

If you have installed the development RPM, you can run PHP scripts interactively, either from your Eclipse IDE (when available) or with the `jrunscript` command:

> `/usr/java/default/bin/jrunscript -l php-interactive`

## Installation from source

For other operating systems, e.g. Solaris, Windows, BSD or Mac-OSX, 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.2 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.4 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`.

- 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:
  `# compile with jdk1.4, use jre1.6 at run-time
  phpize && ./configure --with-java=/usr/java/jdk1.4,/usr/java/jre1.6 && make`

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

- The PHP/Java Bridge can be run as a sub-component of the web server:
  `Do you want to install the Servlet/J2EE back-end (recommended)?
  install j2ee back-end (yes/no): no
  Do you want to start the standalone back-end from a service script?
  install service script (yes/no): no
  `
  The created PHP ini file (usually `java.ini` located in `/etc/php.d/` or `php.ini` located in `c:\winnt\`) should contain:
  `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 back-end automatically starts or re-starts 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:
  `Do you want to install the Servlet/J2EE back-end (recommended)?
  install j2ee back-end (yes/no): no
  Do you want to start the standalone back-end from a service script?
  install service script (yes/no): yes
  run the back-end with limited rights (yes/no): yes
  run the back-end as user (default: apache):
  run the back-end as group (default: apache):
  location of the java executable (/usr/bin/java): /opt/jdk1.5/jre/bin/java
  start now? (yes/no): yes
  `
  The `java.socketname` has been set to the name of the socket, it will be created, if it doesn't exist. The java section of the created PHP ini file (usually `java-standalone.ini` located in `/etc/php.d` or `php.ini` located in `c:\winnt\`) file should contain a `java.socketname` option. The following is an example from Red Hat Enterprise Linux and Fedora:
  `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 back-end as a system service. All available `.ini` options are listed in table 2.

- In a production environment which requires load balancing and fail over or session sharing between PHP, JSP and Servlets it is recommended deploy the back-end into a servlet engine or an application server; a tomcat 5 cluster for example:
  `Do you want to install the Servlet/J2EE back-end (recommended)?
  install j2ee back-end (yes/no): yes
  Enter the location of the autodeploy folder.
  autodeploy (/usr/share/tomcat5/webapps): /opt/SUNWappserver/domains/domain1/autodeploy
  `
  The created PHP ini file (usually `php-servlet.ini` located in `/etc/php.d` or `php.ini` located in `c:\winnt\`) should contain:
  `extension = java.so
  [java]
  java.hosts="127.0.0.1:8080"
  java.servlet=On`
  If you don't have Apache or IIS, install PHP as a CGI or FastCGI binary so that your application server can find it or enable the `php_exec` setting and start the application server.

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 back-end. Must be an integer, if a secure "Unix domain" channel is not available (Windows, Mac OSX). | 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 back-end. | java.log_file="/tmp/php-java-bridge.log"
java.hosts | <none> | Additional bridge hosts which are used when the local back-end 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 `User`, the bridge uses HTTP to communicate with the `java.hosts` back-ends. The option `User` preserves the context, `On` is for backward compatibility and rewrites the context to: `/JavaBridge/JavaBridge.phpjavabridge`.

`;; Make sure that this option is only set
;; if your back-end is deployed in a
;; servlet engine or application server.`
java.servlet=User

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.lib="/tmp/"
java.ext_java_compatibility | Off | Since version 3 the bridge is no longer backward compatible to its predecessor "ext/java": Exact PHP numbers are now represented as java integers, java return values are no longer auto-converted into PHP values. Leave it off, if possible. | java.ext_java_compatibility=On
java.persistent_connections | On | Use persistent connections to the back-end. If this flag is set to `On`, the Apache/Tomcat combination delivers java based content as fast as Tomcat standalone. | java.persistent_connections=Off
java.security_policy | Off | Use the policy file `javabridge.policy` located in the PHP extension directory or the specified policy file. | java.security_policy="c:/windows/javabridge.policy"

## Further information

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

The NEWS file lists the latest user visible changes, development documentation can be found in the `documentation` and `server/documentation` folder.

# FAQ

- #### The bridge doesn't compile on my system!?!

  Please follow the instructions from the INSTALL document as close as possible. In particular the back-end needs the specified versions of GNU autoconf, GNU libtool and GNU automake in the path. Don't try to re-use specialized versions that came with your operating system (e.g. symlink libtool-1.5 to libtool), this will not work; if you don't have autoconf 2.59, automake 1.9 and libtool 1.5.20, you must compile and install them, as described in the INSTALL document. The back-end compilation can be switched off with the `--disable-backend` configure option. A compiled, platform-independent back-end ("JavaBridge.war") can be found in the download folder. If there are problems compiling the bridge code against any PHP version >= 4.3.4 on Windows, Linux/Unix or MacOS, please do not report this problem to the mailing list. Please open a problem report instead (you don't need an account to submit a problem report).

  On RPM based Security Enhanced Linux installations (RHEL, Fedora) please install one of the binary RPMs or compile a binary RPM from the source RPM using the command: `rpmbuild --rebuild php-java-bridge*src.rpm`

  On recent Debian X86 installations, Ubuntu for example, it is also possible to install the RPM binaries: Open the appropriate binary RPM with a file manager and drag and drop the contents of the `lib/php` directory to `/usr/lib/php` and restart apache.

  Table 3. Binary Versions

  Name | ABI
  --- | ---
  php-java-bridge-x.y.z-1.RHEL.i386.rpm | PHP 4 (>= 4.3.2)
  php-java-bridge-x.y.z-1.FC4.i386.rpm | PHP 5.0.x
  php-java-bridge-x.y.z-1.FC5.i386.rpm | PHP 5.1 or PHP 6.x

- #### Can I use java libraries without installing java?

  Yes. Simply ommit the `--with-java=` configure option. The bridge will use the `libgcj` library, which is part of the GNU gcc compiler, to interpret java libraries. This library also uses much less system resources (memory, files) than a "real" java VM.

- #### Does the bridge run native code within my servlet engine or application server?

  No. The bridge back-end is written in pure java, it doesn't use any native code. Native PHP runs within Apache, IIS, a FCGI server or via CGI. If the PHP instance crashes, an error page is returned to the client and a new PHP instance is started for the next request.

- #### How do I make my script state (objects or variables) persistent?

  If you must code it yourself: with e.g. `java_session()->put("buf", $stringBuffer)` or via `$_SESSION["buf"]=$stringBuffer`. The `$_SESSION` is syntactic sugar provided by the php session module, it uses `java_session()` internaly. If you don't want depend on the PHP session module, for example if you have compiled PHP without the `session.so`, use java_session() instead.

  If you use the Java Server Faces framework, you declare the scope of the script in the PHP managed bean descriptor. For example, if the `managed-bean-scope` is changed from `request` to `session`, the framework automatically saves the state of the PHP script instance and restores it when the next request belonging to the same session comes in.

- #### How many threads does the bridge start?

  Request-handling threads are started from a thread pool, which limits the number of user requests to 20 (default), see system property `php.java.bridge.threads`. All further requests have to wait until one of the worker threads returns to the pool.

  When running in a servlet engine, a ContextServer is started which handles the pipe or local socket communication channel.

  When java invokes local scripts outside of a HTTP environment, the bridge starts a HttpServer, a ContextServer and a HttpProxy. The HttpProxy represents the PHP continuation and the HttpServer the request-handling java continuation associated with the JSR223 script.

- #### How do I lock down the VM so that users cannot start threads or call System.exit?

  Usually with a java policy file. An example file has been installed in the php extension directory and can be enabled with: `java.security_policy=On`

- #### Where is my output?

  `System.out` and `System.err` are redirected to the server log file(s). When PHP scripts are invoked from a java framework (Java Server Faces for example), even the PHP output is redirected. For the standalone back-end the output appears in the `/var/log/php-java-bridge.log` or in JavaBridge.log, see .ini option `java.log_file`. For the j2ee back-end the location of the log file(s) depends on the j2ee server configuration.

- #### How do I access enums or inner classes?

  With the `classname$inner` syntax. For example
  `public interface php {
  public class java {
  public enum bridge {JavaBridge, JavaBridgeRunner};
  }
  }
  `
  can be accessed with:
  `<?php
  java_require(getcwd()); // load php.class
  $bridge = new java('php$java$bridge');
  echo $bridge->JavaBridgeRunner;
  ?>
  `
  The above code is not a good programming example but it demonstrates why a different syntax is used to access inner classes.

- #### How do I create a primitive array?

  Primitive types are wrapped by associated java classes. The following example uses `reflect.Array` to create a new `byte` array:
  `$Byte = new JavaClass("java.lang.Byte");
  $byte = $Byte->TYPE;
  $Array = new JavaClass("java.lang.reflect.Array");
  $byteArray = $Array->newInstance($byte, 255);
  $System = new JavaClass("java.lang.System");
  $length = $System->in->read($byteArray);
  $str = new Java("java.lang.String, $byteArray, 0, $length);
  echo "You have typed: $str\n";
  `

- #### How fast is it?

  The following scripts were executed on one 1.688 GHZ x86 cpu running RedHat Fedora Core 4 Linux and Sun jdk1.6.0:

  The PHP 5.1.2 code

  `<?php
  $String = new JavaClass("java.lang.String");
  $buf=new java("java.lang.StringBuffer");
  $i=0;
  java_begin_document();
  while($i<400000) {
  $i=$i+1;
  $buf->append(new java("java.lang.String", $String->valueOf($i)));
  }
  java_end_document();
  print $buf->length() . "\n";
  ?>
  `

  The BSH 2.0 code

  `buf=new java.lang.StringBuffer();
  int i=0;
  while(i<400000) {
  i=i+1;
  buf.append(new String(String.valueOf(i)));
  }
  print (buf.length()); print("\n");
  `

  The ECMAScript ("Mozilla Rhino") code

  `buf = new java.lang.StringBuffer();
  for(i=0; i<400000; i++) buf.append(new String(i));
  print (buf.toString().length());
  `

  Command | Script Engine | Communication Channel | Execution time (real, user, sys)
  --- | --- | --- | ---
  time jrunscript -l php t11.php | PHP5 + PHP/Java Bridge 3.0.8 | named pipes | 0m20.112s, 0m18.999s, 0m0.651s
  time jrunscript -l bsh t11.bsh | BSH 2.0 | none (native code) | 0m21.342s, 0m20.779s, 0m0.291s
  time jrunscript -J-Xmx512M -J-Xms512M -l js t11.js | ECMA script | none (native code) | 1m36.877s, 0m55.398s, 0m0.323s

- #### How do I start a persistent VM?

  If you want to start one persistent VM per HTTP server running on a computer, see the web server installation description. If you want to start one persistent VM per computer, please see Linux RPM package or the application server or servlet engine description.

  Furthermore it is possible to start standalone back-end, for example with the command:
  `java -jar JavaBridge.jar INET_LOCAL:9676 3
  `
  The `php.ini` entry might look like:
  `[java]
  java.hosts = 127.0.0.1:9676
  java.servlet = Off
  `
  Please see the JavaBridge documentation for details.

- #### I want to start the back-end automatically as a sub-component of my HTTP Server. How do I pass my own java options and how do I change the security context and the UID of the java process?

  The bridge uses a wrapper binary which can carry the SUID bit and can be tagged with the SEL security context. This wrapper also allows you to change the standard options, which are: `java -Djava.library.path=... -Djava.class.path=... -Djava.awt.headless=true -Dphp.java.bridge.base=... php.java.bridge.JavaBridge SOCKET_NAME LOG_LEVEL LOG_FILE`. A custom wrapper can be set with:
  `java.wrapper=/path/to/wrapper/binary
  `

  On Unix the bridge terminates the sub-process hierarchy with `SIGTERM`, sleep 5 seconds and `SIGTERM`, if necessary, sleep 5 seconds and `SIGKILL`, if necessary. On Windows the bridge emulates the Unix kill behaviour, the bridge kills the entire sub-process hierarchy so that you can use a `cmd /c` wrapper.

  Please see the wrapper `RunJavaBridge` from the RedHat `php-java-bridge-standalone` RPM for an example.

- #### I want to use the bridge as a replacement for the PHP 4 servlet API, how do I install it into tomcat?

  Download the J2EE binary and copy the `JavaBridge.war` into the tomcat `webapps` folder. After that visit `http://localhost:8080/JavaBridge` and run the supplied PHP examples. Please see `webapps/JavaBridge/WEB-INF/cgi/README` for details.

- #### I want to use PHP for all tomcat applications. Apache and IIS are not available, but performance is important. How do I install it?

  Download and install the J2EE binary: copy `JavaBridge.war` into the tomcat `webapps` folder.

  Copy the `JavaBridge.jar` and the `php-servlet.jar` from the JavaBridge.war into the tomcat `shared/lib` folder. Add the lines marked with a `+` to the tomcat `conf/web.xml`:

  > `
  > <!-- ================== Built In Servlet Definitions ==================== -->
  > + <!-- PHP Servlet -->
  > + <servlet>
  > + <servlet-name>GlobalPhpJavaServlet</servlet-name>
  > + <servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
  > + </servlet>
  > + <!-- PHP CGI Servlet -->
  > + <servlet>
  > + <servlet-name>GlobalPhpCGIServlet</servlet-name>
  > + <servlet-class>php.java.servlet.PhpCGIServlet</servlet-class>
  > + </servlet>
  > <!-- The default servlet for all web applications, that serves static -->
  > <!-- resources. It processes all requests that are not mapped to other -->
  > [...]
  > <!-- ================ Built In Servlet Mappings ========================= -->
  > + <!-- PHP Servlet Mapping -->
  > + <servlet-mapping>
  > + <servlet-name>GlobalPhpJavaServlet</servlet-name>
  > + <url-pattern>*.phpjavabridge</url-pattern>
  > + </servlet-mapping>
  > + <!-- CGI Servlet Mapping -->
  > + <servlet-mapping>
  > + <servlet-name>GlobalPhpCGIServlet</servlet-name>
  > + <url-pattern>*.php</url-pattern>
  > + </servlet-mapping>
  > <!-- The servlet mappings for the built in servlets defined above. Note -->
  > <!-- that, by default, the CGI and SSI servlets are *not* mapped. You -->
  > </web-app>
  > `

  To test the above settings create a directory `testapp` and copy the `test.php` file from the `JavaBridge.war` into this folder. Type `cd testapp; jar cf ../testapp.war *` and copy the testapp.war into the tomcat `webapps` folder. Restart tomcat, browse to `http://yourHost.com:8080/testapp/test.php`.

  Check if the PHP Fast-CGI server is running. The process list should display 20 (default) PHP instances waiting in the PHP Fast-CGI pool. If not, check if your PHP binary has been compiled with Fast-CGI enabled. Copy a Fast-CGI enabled binary into the `webapps/JavaBridge/WEB-INF/cgi/` folder, if necessary.

- #### How do I create a standalone PHP web application for distribution and how can users deploy it into tomcat?

  Create a directory `myApplication`, create the directories `myApplication/WEB-INF/lib/` and `myApplication/WEB-INF/cgi/`. Download the J2EE binary and copy the `JavaBridge.jar` and the `php-servlet.jar` from the JavaBridge.war to the `myApplication/WEB-INF/lib/` folder. Copy the contents of the CGI folder to `myApplication/WEB-INF/cgi/`. Create the file `myApplication/WEB-INF/web.xml` with the following content:

  > `
  > <web-app>
  > <!-- PHP Servlet -->
  > <servlet>
  > <servlet-name>PhpJavaServlet</servlet-name>
  > <servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
  > </servlet>
  > <!-- PHP CGI processing servlet, used when Apache/IIS are not available -->
  > <servlet>
  > <servlet-name>PhpCGIServlet</servlet-name>
  > <servlet-class>php.java.servlet.PhpCGIServlet</servlet-class>
  > </servlet>
  > <!-- PHP Servlet Mapping -->
  > <servlet-mapping>
  > <servlet-name>PhpJavaServlet</servlet-name>
  > <url-pattern>*.phpjavabridge</url-pattern>
  > </servlet-mapping>
  > <!--PHP CGI Servlet Mapping -->
  > <servlet-mapping>
  > <servlet-name>PhpCGIServlet</servlet-name>
  > <url-pattern>*.php</url-pattern>
  > </servlet-mapping>
  > <!-- Welcome files -->
  > <welcome-file-list>
  > <welcome-file>index.php</welcome-file>
  > </welcome-file-list>
  > </web-app>
  > `

  Copy the files `sessionSharing.jsp` and `sessionSharing.php` from the `JavaBridge.war` to `myApplication` and create `myApplication.war`, for example with the commands: `cd myApplication; jar cf ../myApplication.war *`.

  The web archive can now be distributed, copy it to the tomcat `webapps` directory and re-start tomcat. Visit `http://localhost/myApplication/sessionSharing.php` and `http://localhost/myApplication/sessionSharing.jsp`.

- #### I want to use Apache/IIS as a front-end and tomcat as a back-end. How do I enable PHP for all my applications?

  Download and install the J2EE binary: copy `JavaBridge.war` into the tomcat `webapps` folder. Check if the tomcat `webapps` directory is shared with the Apache/IIS `htdocs` directory. If not, change the Apache/IIS setting, the following example is for Apache 2. Edit e.g. `/etc/httpd/conf/httpd.conf` as follows:

  > `# documents. By default, all requests are taken from this directory, but
  > # symbolic links and aliases may be used to point to other locations.
  > #
  > -DocumentRoot "/var/www/html"
  > +DocumentRoot "/var/lib/tomcat5/webapps"
  > #
  > # Each directory to which Apache has access can be configured with respect
  > #
  > # This should be changed to whatever you set DocumentRoot to.
  > #
  > -<Directory "/var/www/html">
  > +<Directory "/var/lib/tomcat5/webapps">
  > `

  Edit the `php.ini` or add a file `php-tomcat.ini` to the directory which contains the PHP module descriptions (usually `/etc/php.d/`), so that it contains:

  > `[java]
  > java.hosts = 127.0.0.1:8080
  > java.servlet = On
  > `

  To test the above settings create a directory `testapp` and copy the `sessionSharing.php` file from the `JavaBridge.war` into this folder. Type `cd testapp; jar cf ../testapp.war *` and copy the testapp.war into the tomcat `webapps` folder. Restart Apache or IIS and tomcat, browse to `http://localhost/testapp`, click on sessionSharing.php and check the generated cookie value. The `path` value must be `/`.

- #### I want to use Apache/IIS as a front-end and tomcat as a back-end. How do I enable PHP and JSP for all my applications?

  Download the J2EE binary and copy the `JavaBridge.jar` and the `php-servlet.jar` from the JavaBridge.war into the tomcat `shared/lib` folder. Add the lines marked with a `+` to the tomcat `conf/web.xml`:

  > `
  > <!-- ================== Built In Servlet Definitions ==================== -->
  > + <!-- PHP Servlet -->
  > + <servlet>
  > + <servlet-name>GlobalPhpJavaServlet</servlet-name>
  > + <servlet-class>php.java.servlet.PhpJavaServlet</servlet-class>
  > + </servlet>
  > <!-- The default servlet for all web applications, that serves static -->
  > <!-- resources. It processes all requests that are not mapped to other -->
  > [...]
  > <!-- ================ Built In Servlet Mappings ========================= -->
  > + <!-- PHP Servlet Mapping -->
  > + <servlet-mapping>
  > + <servlet-name>GlobalPhpJavaServlet</servlet-name>
  > + <url-pattern>*.phpjavabridge</url-pattern>
  > + </servlet-mapping>
  > <!-- The servlet mappings for the built in servlets defined above. Note -->
  > <!-- that, by default, the CGI and SSI servlets are *not* mapped. You -->
  > </web-app>
  > `

  Check if the tomcat `webapps` directory is shared with the Apache/IIS `htdocs` directory. If not, change the Apache/IIS setting, the following example is for Apache 2. Edit e.g. `/etc/httpd/conf/httpd.conf` as follows:

  > `# documents. By default, all requests are taken from this directory, but
  > # symbolic links and aliases may be used to point to other locations.
  > #
  > -DocumentRoot "/var/www/html"
  > +DocumentRoot "/var/lib/tomcat5/webapps"
  > #
  > # Each directory to which Apache has access can be configured with respect
  > #
  > # This should be changed to whatever you set DocumentRoot to.
  > #
  > -<Directory "/var/www/html">
  > +<Directory "/var/lib/tomcat5/webapps">
  > `

  Now that tomcat knows how to handle PHP `.phpjavabridge` requests and Apache or IIS can access the tomcat webapps, connect the two components: Edit the `php.ini` or add a file `php-tomcat.ini` to the directory which contains the PHP module descriptions (usually `/etc/php.d/`), so that it contains:

  > `[java]
  > java.hosts = 127.0.0.1:8080
  > java.servlet = User
  > `

  The above `User` setting enables session sharing between PHP and JSP, it forwards from `http://host/myApp/foo.php` to the tomcat back-end at `127.0.0.1:8080` using the request `PUT /myApp/foo.phpjavabridge`. This triggers the `GlobalPhpJavaServlet` configured in the tomcat `web.xml`.

  Now you need to do the same for JSP. Unlike the PHP/Java Bridge, which only forwards embedded java statements, the tomcat `mod_jk` adapter must forward all JSP requests. Download and install `mod jk`, for example `jakarta-tomcat-connectors-1.2.14.1-src.tar.gz`, extract the file into a folder and type the following commands:

  > `cd jakarta-tomcat-connectors-1.2.14.1-src/jk/native/
  > ./configure --with-apxs && make && su -c "make install"
  > `

  Add the following lines to the end of the `httpd.conf`, the following example is for Apache 2:

  > `LoadModule jk_module modules/mod_jk.so
  > JkAutoAlias /var/lib/tomcat5/webapps
  > JkMount *.jsp ajp13
  > `

  To test the above settings create a directory `testapp` and copy the `sessionSharing.php` and `sessionSharing.jsp` from the `JavaBridge.war` into this folder. Type `cd testapp; jar cf ../testapp.war *` and copy the testapp.war into the tomcat `webapps` folder. Restart Apache or IIS and tomcat, browse to `http://localhost/testapp`, click on sessionSharing.php and check the generated cookie value. The `path` value must be `/testapp`. Click on sessionSharing.jsp.

- #### How does the bridge handle OutOfMemoryErrors?

  OutOfMemoryErrors may happen because a cached object cannot be released, either because

  1. the object is permanently referenced by a request-handling thread or
  2. the object has been entered into the session or application store or
  3. the object is referenced by a thread outside of the scope of the PHP/Java Bridge.

  When a `java.lang.OutOfMemoryError` reaches the request-handling thread, the PHP/Java Bridge thread pool removes the thread from its pool and writes a message `FATAL: OutOfMemoryError` to the PHP/Java Bridge log file. The session store is cleaned and all client connections are terminated without confirmation.

  If the OutOfMemoryError persists, this means that a thread outside of the PHP/Java Bridge has caused this error condition.

  The following code example could cause an OutOfMemoryError:
  `<?php
  session_start();
  if(!$_SESSION["buffer"]) $_SESSION["buffer"]=new java("java.lang.StringBuffer");
  $_SESSION["buffer"]->append(...);
  ?>`

  OutOfMemory conditions can be debugged by running the back-end with e.g.:
  `java -agentlib:hprof=heap=sites -jar JavaBridge.jar
  `

- #### The EJB example works with the Sun J2EE server, but in JBoss I get a ClassCastException, what's wrong?

  It's a JBoss problem, although this problem may also appear in other application servers which do not strictly separate the application/bean domains. The JavaBridge.war already contains the `documentClient.jar` as a library, so JBoss references the library classes instead of the bean classes. Just remove the `documentClient.jar` from the `JavaBridge.war`, re-deploy `JavaBridge.war` and run the test again.

  In JBoss' default setup the code:

  > `// access the home interface
  > $DocumentHome = new JavaClass("DocumentHome");
  > $PortableRemoteObject = new JavaClass("javax.rmi.PortableRemoteObject");
  > $home=$PortableRemoteObject->narrow($objref, $DocumentHome);
  > `

  refences the `DocumentHome` from the library, which is assignment-incompatible to `DocumentHome` from the enterprise bean (`DocumentHome@WebAppClassLoader` != `DocumentHome@BeanClassLoader`), so you get a ClassCastException in `narrow`.

  In contrast the Sun J2EE server correctly separates the beans/applications; the `$objref` is unique proxy generated by a parent of the `WebAppClassLoader`, so that `narrow` can always cast the proxy to `DocumentHome@WebAppClassLoader`, even if a class with the same name is already available from the `WebAppClassLoader`.

# Related

- A PHP IDE.
- A tutorial how to use the predecessor "ext/java".
- A commercial free (GPL) PHP engine written in pure java.
- A commercial non-free 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.