PHP/Java Bridge FAQ

This file contains answers to frequently asked questions. Please see http://php-java-bridge.sourceforge.net for more information.

General questions

Which alternatives exist?

There are at least 4 other php to java bridges which offer a similar API. One was distributed with PHP 4.0.0 and has been discontinued. Two other bridges are proprietary software, built into a vendor-specific framework from Zend or a J2EE application server from Caucho. Furthermore IBM's Zero framework for Eclipse contains a PHP interpreter written in pure Java and a php to java bridge which can call Java methods in-process.

The only free alternatives are SOAP and XML-RPC, which are up to 50 times slower than the XML protocol implementation used by this PHP/Java Bridge.

Does it support PHP 4?

No. Use PHP/Java Bridge version 4.3.2 or below instead.

What about portability?

A portable PHP application can use the "new Java(...)" constructor and the "java(...)" function. To access a Java type use

$System = java("java.lang.System");
To create an instance of a Java type use
$hashMap = new java("java.util.HashMap");

Do I need a Java Application Server or Servlet Engine?

Not necessarily. But a servlet engine or J2EE service is easier to install and to handle than a standalone Java service.

Ho do I enable logging?

Copy log4j.jar into java.ext.dirs. Example for JDK 6:

cp log4j.jar /usr/java/packages/lib/ext

Start the log4j viewer. Example for JDK 6:

/opt/jdk1.6/bin/java org.apache.log4j.chainsaw.Main

Start the application server with the options -Dphp.java.bridge.default_log_level=LEVEL. Example for tomcat:

JAVA_HOME=/opt/jdk1.6 JAVA_OPTS="-Dphp.java.bridge.default_log_level=5" bin/catalina.sh run
Example for the standalone container:
java -Dphp.java.bridge.default_log_level=5 -jar JavaBridge.jar SERVLET:8080

How can I configure the bridge?

Useful options which can be set before the Java.inc/Mono.inc is loaded are:

define ("JAVA_DEBUG", false);
define ("JAVA_HOSTS", "127.0.0.1:8080");
define ("JAVA_PIPE_DIR", null);
require_once ("java/Java.inc");
...
Please see the Options.inc for details.

Server-side options can be set in the php.java.bridge.global.properties file, see the JavaBridge.jar zip file (contained in the JavaBridge.war zip file) for details.

How do I start the bridge back end when there's another Java VM listening on port 8080?

Simply deploy the PHP/Java Bridge web archive into the servlet engine or application server listening on port 8080. Or use a different port.

What's the difference between SERVLET_LOCAL:8080 and INET_LOCAL:8080?

The standalone option SERVLET_LOCAL emulates a servlet engine and starts a HTTP server which can select the fastest channel supported on this operating system. On Linux this is a named pipe created in /dev/shm or INET_LOCAL as a fall back.

INET_LOCAL always uses local TCP socket communication.

Whenever I reboot my computer I have to start the bridge back end again. How can I automate this?

Download and install a servlet engine or J2EE server, for example tomcat.

Do I have to require Java.inc in each of my scripts? Isn't that very slow?

The PHP/Java Bridge library Java.inc must be included before it can be used. Therefore the scripts should contain the statement

  require_once("...java/Java.inc");
at the beginning of the script. PHP compiles and caches PHP scripts, the Java.inc library is loaded only once.

Can I use Java libraries without installing java?

Yes. On a GNU operating system (e.g.: GNU/Linux, GNU/windows (aka "cygwin"), ...) you can use the GCC compiler to compile Java classes to native code. Simply compile the C based extension and omit the --with-java= configure option. The bridge will use the libgcj library, which is part of the GNU gcc compiler. This library also uses much less system resources (memory, files) than a "real" Java VM.

I get a blank page or some other error!?!

Check the PHP error log, see your php.ini file for details. If the command:

echo '<?php require_once("http://localhost:8080/JavaBridge/java/Java.inc"); echo java("java.lang.System")->getProperties();?>' | php -n -d allow_url_include=On
works in the shell but not within apache, then there's something wrong with your php.ini file.

How do I create a distributable PHP web application and how can users publish PHP/Java pages?

Check if the ISP supports Java. Look for a servlet engine like "tomcat" or a J2EE application server like "resin". Check if your ISP supports PHP >= 4.3.2.

In the following example we'll call our web context "webContext".

Unzip the JavaBridge.jar file and edit Java.inc, replace 8080 with your j2EE port number and JAVA_SERVLET=On to JAVA_SERVLET=User. Example for Linux:

mkdir webContext
cd webContext
jar xvf ../JavaBridge.war
Edit java/Java.inc as follows (lines marked with a "-" should be removed, lines marked with a "+" should be added):
  if(!defineHostFromInitialQuery($JAVA_BASE)) {
- define("JAVA_HOSTS", "127.0.0.1:8080");
+ define("JAVA_HOSTS", "127.0.0.1:YOUR_J2EE_PORT_NUMBER");
- define("JAVA_SERVLET", "On");
+ define("JAVA_SERVLET", "User");
  }

Create a Java web archive, for example "webContext.war". Example for Linux:

# ... still within the webContext directory ...
cp ../myJavaLibs/*.jar WEB-INF/lib/
cp ../myPhpPages/*.php .
jar cvf ../webContext.war *
Users can deploy it into their J2EE application server or servlet engine. Example for Linux:
cp ../webContext.war /usr/share/tomcat5/webapps/

Then they need to copy or symlink the created web context "webContext" (or whatever you've called it) to their Apache or IIS htdocs (sometimes called "public_html") directory. Example for Linux:

ln -s /usr/share/tomcat5/webapps/webContext $HOME/public_html/webContext

After restarting the HTTP server, they can browse to http://HOSTNAME/webContext/yourPhpScript.php. Again, replace the web context "webContext" with the name of your web context.

NOTE: If users want to run the Java VM on a different computer, they need to start Tomcat or the J2EE server on that computer using the option -Dphp.java.bridge.promiscuous=true. And change the 127.0.0.1 above to the IP address of the computer running the Java VM and make sure that the computer cannot be accessed directly from the internet!

Can I use Python instead of PHP?

Yes, see the examples folder from the source download.

Can I access Mono or .NET libraries using the pure PHP implementation?

Yes, there's a PHP library "Mono.inc" generated from "Java.inc" and a "MonoBridge.exe" generated from "JavaBridge.jar". If you want to compile from source, use the configure option --with-mono.

Class loading questions

How do I load Java libraries?

With java_require("myApplication.jar;myLib1.jar;myDriver1.jar;...");. See the README for details.

Where can I store my java libraries for the PHP/Java Bridge?

In php.java.bridge.base/lib.

When the system property php.java.bridge.base is not set, libraries are loaded from $HOME/lib where $HOME denotes the home directory of the person or component which has started the java VM.

If libraries should be available globally, store them in java.ext.dirs, for example in /usr/share/java/ext.

If a library is not yet API-stable, store it into a sub directory of the lib directory and use the java_require() procedure. For example java_require("myLibs0.2/foo.jar") loads foo.jar from php.java.bridge.base/lib/myLibs0.2.

Why can't Apache load my /foo/bar/baz.jar file?

It probably doesn't have the permission to access it. Check if baz.jar is a valid Java archive and if its main class is public. Try to disable Security Enhanced Linux and store the jar file into a folder accessible by the apache user and then extract the required Security Enhanced Linux permissions from the audit log.

Why do I get a ClassNotFoundException?

You probably haven't required the relevant Java library. Or the class doesn't exist or it is not public or it throws a java.lang.Error during initialization. Check which library exports the feature and add the library to the java_require() statement.

Why do I get a NoClassDefFoundError?

Because Java doesn't have a module system. All interconnected libraries must be loaded with a single java_require() call. See the README for details.

I cannot require my JDBC driver!?!

Please re-read the class loading section. The following code loads all interconnected libraries using a single java_require() call:

  java_require("myApplication.jar;myJdbcDriver.jar");
   ...
  $myApplication->callWithMyJdbcDriver();

The following incorrect code fails because the application (the "JavaBridge.jar" in this case) cannot be accessed by the jdbc driver. This constraint is checked by the DriverManager:

  java_require("myJdbcDriver.jar"); // WRONG!
  new java("my.jdbc.Driver");
  java("java.sql.DriverManager")->getDriver("myJdbcURL"); // FAILS!
If you really need to access the driver directly from PHP code, either use the driver API directly or load "JavaBridge.jar" and "myJdbcDriver.jar" from the same class loader so that the DriverManager can link them together. Use the extra library directory (usually ~/lib/) or the global repository (usually /usr/java/packages/lib/ext).

How do I load impure Java libraries?

You can't. Java libraries must be pure Java.

Please read the documentation of your J2EE server, Servlet engine or Java VM to see if and how the environment can handle impure Java libraries. A common approach is to store the Java part in java.ext.dirs and the native part in java.library.path.

J2EE/Servlet questions

How do I set up a load balancer for the PHP/Java Bridge cluster?

Set up the PHP/Java Bridge cluster as described below. The example uses two nodes named "carlos" and "diego". The HTTP server front end runs on the web server "timon".

Install Apache 2.2.0 or higher.

Enable proxy_module and proxy_balancer_module. The following example is for Linux (lines marked with "+" should be added to the conf/httpd.conf file):

   LoadModule rewrite_module modules/mod_rewrite.so
 + LoadModule proxy_module modules/mod_proxy.so
 + LoadModule proxy_balancer_module modules/mod_proxy_balancer.so
   LoadModule cache_module modules/mod_cache.so

Add the following code to the bottom of your conf/httpd.conf file:

ProxyPass /JavaBridge balancer://mycluster maxattempts=2
<Proxy balancer://mycluster>
  BalancerMember http://diego:8080/JavaBridge
  BalancerMember http://carlos:8080/JavaBridge
</Proxy>
<Location /balancer-manager>
  SetHandler balancer-manager
  Deny from all
  Allow from 127.0.0.1
</Location>

Start the cluster nodes on "carlos" and "diego".

Browse to http://timon/JavaBridge/ (note the trailing slash) and click on the test.php. Click on refresh. Check if both nodes respond.

Browse to http://timon/JavaBridge/sessionSharing.php and click on refresh. Check the cookie value.

Browse to http://timon/balancer-manager/.

Please see the mod_rewrite documentation for more information how to rewrite incoming URLs.

Ho do I set up a tomcat cluster?

Download tomcat 5 or higher, a Java JRE 5 or higher and the PHP/Java Bridge 4.1.6 or higher.

The following example uses two nodes running on two machines called "carlos" and "diego". The web server is running on a third machine which has full access to both nodes (at least it needs access to the ports from the range [9267, [9367).

On all nodes: Extract the tomcat distribution into a directory.

On "diego" add the following to conf/server.xml:

<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
  channelSendOptions="8">
  <Manager className="org.apache.catalina.ha.session.DeltaManager"
    expireSessionsOnShutdown="false"
    notifyListenersOnReplication="true"/>
  <Channel className="org.apache.catalina.tribes.group.GroupChannel">
    <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
    address="diego"
    port="4000"
    autoBind="100"
    selectorTimeout="5000"
    maxThreads="6"/>
  </Channel>
</Cluster>

On "carlos" add the following to conf/server.xml:

<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"
  channelSendOptions="8">
  <Manager className="org.apache.catalina.ha.session.DeltaManager"
    expireSessionsOnShutdown="false"
    notifyListenersOnReplication="true"/>
  <Channel className="org.apache.catalina.tribes.group.GroupChannel">
    <Receiver className="org.apache.catalina.tribes.transport.nio.NioReceiver"
    address="carlos"
    port="4000"
    autoBind="100"
    selectorTimeout="5000"
    maxThreads="6"/>
  </Channel>
</Cluster>

Copy the "JavaBridge.war" into the "webapps" directory on "diego" and "carlos" and start both nodes. For example with the command:

JAVA_OPTS="-Dphp.java.bridge.promiscuous=true" JAVA_HOME=/opt/jdk1.5 bin/catalina.sh run

Start the web server on the third computer "timon". For example with the command:

apachectl restart

Create a PHP script called "sessionSharing-diego.php" and copy it into the web server document root (usually "/var/www/html" or "~/public_html") on "timon":

<?php
require_once("http://diego:8080/JavaBridge/java/Java.inc"); // change to "java/Java.inc" if you use a load balancer
$session = java_session();
if(is_null($session->get("counter")))
  $session->put("counter", new Java("java.lang.Integer", 1));

$counter = java_values($session->get("counter"));
print "HttpSession variable \"counter\": $counter<br>\n";
$next = new Java("java.lang.Integer", $counter+1);
$session->put("counter", $next);
?>

Create a PHP script called "sessionSharing-carlos.php" and copy it into the web server document root (usually "/var/www/html" or "~/public_html") on "timon":

<?php
require_once("http://carlos:8080/JavaBridge/java/Java.inc"); // change to "java/Java.inc" if you use a load balancer
$session = java_session();
if(is_null($session->get("counter")))
  $session->put("counter", new Java("java.lang.Integer", 1));

$counter = java_values($session->get("counter"));
print "HttpSession variable \"counter\": $counter<br>\n";
$next = new Java("java.lang.Integer", $counter+1);
$session->put("counter", $next);
?>

Start a web brower and remove all cookies

Browse to http://timon/sessionSharing-carlos.php and check the generated cookie. It should have the key "JSESSIONID", host attribute "timon" and the path attribute "/". The value should be "1". Click on the browser refresh button to increase the value.

Use the same browser window and navigate to http://timon/sessionSharing-diego.php and check if there is still only one cookie with the same attributes as before. The value should be "3"

Use the same browser window and navigate to http://timon/sessionSharing-carlos.php and check if there is still only one cookie with the same attributes as before. The value should be "4".

Switch off "diego" and start it again.

Use the same browser window and navigate to http://timon/sessionSharing-diego.php and check if there is still only one cookie with the same attributes as before. The value should be "5"

Switch off "carlos".

Use the same browser window and navigate to http://timon/sessionSharing-carlos.php and check if you get an exception.

Start "carlos".

Use the same browser window and navigate to http://timon/sessionSharing-carlos.php and check if there is still only one cookie with the same attributes as before. The value should be "6"

Please see your HTTP server documentation and the description above how to set it up as a load balancer. This differs from the architecture described above in that the load balancer forwards the requests to the nodes and the nodes run PHP using the FastCGI mechanism.

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

Check if your PHP cgi binary supports the -b flag. If not, compile PHP with the --enable-fastcgi option

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. Uncomment the shared_fast_cgi_pool parameter in the JavaBridge/WEB-INF/web.xml and 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>
+ <init-param>
+ <!-- Remember to set the shared_fast_cgi_pool option -->
+ <!-- in JavaBridge/WEB-INF/web.xml to On, too. -->
+ <param-name>shared_fast_cgi_pool</param-name>
+ <param-value>On</param-value>
+ </init-param>
+ </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 5 (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 java.host and java.servlet options in your Java.inc or, if you use the C implementation, the php.ini:

[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 java.host and java.servlet options in your Java.inc or, if you use the C implementation, the php.ini:

[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.

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 the Apache, IIS, CGI container usually starts a new PHP instance for the next request.

On Windows some PHP binaries do not support HTTPS/SSL

If you see the message:

Warning: fsockopen() [function.fsockopen]: unable to connect to ssl://127.0.0.1:8443 (Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?)
this means that PHP cannot connect back to the official SSL port. Please check the "Registered Stream Socket Transports" from the phpinfo() (see the test.php page), it should display: tcp, udp, ssl, sslv3, sslv2, tls. If not, please recompile PHP with SSL enabled, use the flag --with-openssl.

A workaround is to use the official non-SSL port or to open a dedicated local port for the PHP-Java communication. The following example is for Tomcat:

    Disable override_hosts in the web application WEB-INF/web.xml:
    <init-param>
    <param-name>override_hosts</param-name>
    <param-value>Off</param-value>
    </init-param>
    Open a local port in the tomcat conf/server.xml (only necessary if you have disabled the official non-SSL port):
    <Service name="Catalina">
    [...]
    <Connector port="9157" address="127.0.0.1" />
    [...]
    </Service>
    Set the communication port in the PHP .ini (the phpinfo() or test.php displays the location of the responsible .ini file):
    [java]
    java.hosts = 127.0.0.1:9157
    java.servlet = User
If you want to use the official non-SSL port (usually port number 8080), change the java.hosts line accordingly.

Restart the application server or servlet engine. Check the settings by running phpinfo() or by visiting the test.php page.

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 a 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.

How do I install PHP into the Nutch, Spring, JSF, ..., Framework?

By providing JSR 223 based PHP beans and a description how to manage them, as usual. The code

javax.script.ScriptEngine e =
php.java.script.EngineFactory.getInvocablePhpScriptEngine (this,
application,
request, response);
can be used to access the JSR 223 ScriptEngine from the framework, provided that a listener has been configured in the WEB-INF/web.xml:
<listener> <listener-class>php.java.servlet.ContextLoaderListener</listener-class> </listener>

General runtime questions

How do I reference a class w/o creating an instance?

With the java function, for example: java("java.lang.System").

The function is defined in http://localhost:8080/JavaBridge/java/Java.inc as:

function java($clazz) {
  static $classMap = array();
  if(array_key_exists($clazz, $classMap)) return $classMap[$clazz];
  return classMap[$clazz]=new JavaClass($clazz);
}

Why does java_context()->getHttpServletRequest()->getSession() return null?

PHP scripts must explicitly allocate a session with java_session(). For example:

java_session();
// now the (Remote-)HttpServletRequest knows about the session:
echo java_context()->getHttpServletRequest()->getSession();

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 VMBridge.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 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.

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

The PHP 5.2.2 code

<?php
$buf=new java("java.lang.StringBuffer");

$i=0;
while($i<400000) {
  $i=$i+1;
  $buf->append($i);
}

print $buf->length() . "\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());

CommandScript EngineCommunication ChannelExecution time (real, user, sys)
time jrunscript -l php t11.phpPHP5 + PHP/Java Bridge 4.3.3named pipes0m18.703s,
0m16.209s,
0m0.138s
time jrunscript -l js t11.jsECMA scriptnone (native code)0m15.338s,
0m14.996s,
0m0.116s

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

How can PHP classes extend Java classes and Java methods?

By using java_closure() and the visitor pattern for example. The tests.php5 folder contains a script_api.php example which shows how to implement java.lang.Runnable to run multiple PHP threads, concurrently accessing a shared resource.

How can I execute PHP code on the server?

With java_begin_document()/java_end_document(). For example:

  java_begin_document();
  $s = new Java("java.lang.StringBuffer");
  for($i=0; $i<10000; $i++) $s->append($i);
  java_end_document();
The above code sends the PHP code as an XML image to the server and executes it there.

How can I convert a Java object into a PHP value?

With java_values(). For example:

  $s = new Java("java.lang.String");
  $c = $chr = $s->toCharArray();
  print (java_values($s));
  print_r(java_values($c));

How can I convert a PHP object into a Java object?

With java_closure(). For example:

  class Foo {
   function toString() {return "php::foo";}
  }
  $foo = new Foo();
  $jObj = java_closure($foo);
  $String = new Java("java.lang.String");
  echo $String->valueOf($jObj);

How do I call JSP tags from PHP?

Example:

require_once("http://localhost:8080/JavaBridge/java/Java.inc");
java_require("myLibs/baz-taglib.jar");
$tag = new Java("foo.bar.BazTag");

$session = java_session();
$ctx = java_context();
$servlet = $ctx->getAttribute("php.java.servlet.Servlet");
$response = $ctx->getAttribute("php.java.servlet.HttpServletResponse");
$request = $ctx->getAttribute("php.java.servlet.HttpServletRequest");
$factory = java("javax.servlet.jsp.JspFactory")->getDefaultFactory();
$pc = $factory->getPageContext($servlet, $request, $response, null, true, 8192, false);

$tag->setPageContext($pc);
$value = $tag->doStartTag();
if(($value != Java("javax.servlet.jsp.tagext.Tag")->SKIP_BODY) {
  if($value != Java("javax.servlet.jsp.tagext.Tag")->EVAL_BODY_INCLUDE)) {
    $tag->setBodyContent($pc->pushBody());
    $tag->doInitBody();
  }
  do {
    ...
  } while($tag->doAfterBody() == Java("javax.servlet.jsp.tagext.BodyTag")->EVAL_BODY_AGAIN)
}
if($value != Java("javax.servlet.jsp.tagext.Tag")->EVAL_BODY_INCLUDE) $pc->popBody();
$tag->doEndTag();

The generated content (if any) can be retrieved from the servlet output stream with:

java_values($response->getBufferContents();

Please see the php_java_lib/JspTag.php and tests.php5/tag.php for details.

How does the bridge support Java generics?

You can ignore the parameter type.

Java doesn't support real generics on byte-code level. The generics in JDK 1.5 and above are implemented as "erasures"; they are syntactic sugar, useful only for the Java compiler. The generated byte-code is the same as in JDK 1.4.

What about Java 5 varargs?

Pass them as a PHP array. Example:

<?php require_once("http://localhost:8080/JavaBridge/java/Java.inc");
$here=getcwd(); java_require("$here/varargs.jar");
$t1 = new java('Varargs$Test', 1);
$t2 = new java('Varargs$Test', 2);
echo java("Varargs")->varargs(array($t1, $t2));
?>

public class Varargs {
 public static class Test {
  public int i;
  public Test (int i) {
   this.i = i;
  }
  public String toString() {
   return String.valueOf(i);
  }
 }
 public static String varargs(Test ...tests) {
  StringBuffer buf = new StringBuffer();
  for (Test test : tests) {
   buf.append(test);
  }
  return buf.toString();
 }
}