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 about the C- or pure PHP implementation

Do I need a Java Application Server or Servlet Engine?

No. The bridge and the VM can run as a sub component of IIS or Apache. The C based extension automatically starts a VM in the minit() and terminates it in the mshutdown() hook. The request-handling threads attach themselfs to the persistent VM using the PHP/Java Bridge protocol.

What's the advantage/disadvantage of the pure PHP implementation?

Both implementations support the same features. But since PHP doesn't contain a "just in time compiler", the C based extension module is 2 to 10 times faster than the pure PHP implementation (depending on whether a PHP opcode cache is used).

The pure PHP implementation needs an external Java process. It can be started with java -jar JavaBridge.jar SERVLET:8080, but it is recommended to start the external Java VM via a J2EE server or servlet engine. The tomcat servlet engine can be used to start Java as a system service on Windows and Linux.

The C based implementation compiles and works on all operating systems, including Windows. But we cannot provide binaries for all operating systems. If you cannot compile C code, use the pure PHP implementation instead.

Why is Java.inc obfuscated?

The pure PHP implementation contained in Java.inc is created during compilation from the other *.inc files located in the java folder. Since some older PHP implementations don't have a opcode cache (sometimes called "accelerator"), we have removed all comments and white space from the source files. Use

  require_once("http://localhost:8080/JavaBridge/java/JavaBridge.inc");
if you want to run the original code.

Can I use Java libraries without installing java?

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

Can I compile the C based implementation of the PHP/Java Bridge without compiling the Java classes to native code?

Yes. If your C compiler cannot compile Java classes to native code, use the --disable-backend configure option and add a java.java=/path/to/your/java/executable option to your php.ini [java] section.

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?

No. You need to compile the C implementation and use the configure option --with-mono.

How can I configure the bridge?

The three config options java.log_level, java.servlet and java.hosts can be changed in the php.ini file (C based implementation) or Java.inc, which is created from Options.inc (pure PHP implementation).

What if the Java back end is not available anymore?

Then the bridge uses the next entry from the java.hosts list. If there are no more entries, the php function java_server_name() returns null and all other java procedures cannot be used anymore.

Can I set the java.hosts option at run-time?

Yes. Simply use require_once("http://YOURSERVER:PORT/CONTEXT/java/Java.inc");

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.

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

Tomcat starts and stops as a system service on Unix and Windows.

Download and install the tomcat servlet engine, deploy the PHP/Java Bridge web archive into the tomcat servlet engine and configure it so that it only listens for requests from local PHP scripts (default).

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.

I get a blank page!?!

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.

Running Java as a sub component of Apache or IIS

How do I hard code the path to java into the C extension?

With the configure option --with-java=COMPILETIME_JAVA_HOME,RUNTIME_JAVA_HOME. For example:

phpize &&
./configure --with-java=/opt/jdk1.5,/usr/java/default &&
make &&
make install

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

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 for an example.

Class loading questions

How do I load Java libraries?

With java_require("foo.jar;bar.jar;...");. See the README for details.

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

The java_require() uses the current class loader, not the bootstrap loader. Use:

  java_require("foo.jar");
   ...
  Class.forName("foo",true,Thread.currentThread().getContextClassLoader());
instead.

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

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?

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 PHP beans and a description how to manage them, as usual. IOC (sometimes called "dependency injection") requires that you give up control so that the framework can call you when it becomes necessary. The code

class Bean { ... }
java_context()->call(java_closure(new Bean())) || header("$framework");
can be used to pass control from the web server to the framework running on a J2EE node.

The standard java script interface or the proxy used by the invocable interface can be used to call from the framework running on a J2EE node into the allocated PHP scripts running on the web server. The following excerpt from the JSF implementation calls methods from the above PHP bean:

((Invocable)((PhpFacesContext)FacesContext.getCurrentInstance()).getScriptEngine(this, new URL(phpScript))).invoke(method, args);
Please see the JSF implementation for a reference.

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

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());

CommandScript EngineCommunication ChannelExecution time (real, user, sys)
time jrunscript -l php t11.phpPHP5 + PHP/Java Bridge 3.0.8named pipes0m20.112s,
0m18.999s,
0m0.651s
time jrunscript -l bsh t11.bshBSH 2.0none (native code)0m21.342s,
0m20.779s,
0m0.291s
time jrunscript -J-Xmx512M -J-Xms512M -l js t11.jsECMA scriptnone (native code)1m36.877s,
0m55.398s,
0m0.323s

How fast is the pure PHP/Java implementation compared with the C based implementation or JSP?

On modern operating systems (Windows, Solaris and Linux) and PHP >= 5.1.4 with an opcode cache enabled, the pure PHP implementation is only 2-3 times slower than either the C based implementation or compiled JSP (=Java servlets).

The following table displays the result of the command:

time for i in `seq 200`
  do wget -O/dev/null -o/dev/null http://localhost:8080/JavaBridge/sessionSharing.[php|jsp]
done
OSPHP (tcp sockets)PHP (named pipes)JSP
Linux (RedHat Fedora 6)0m9.465s0m9.477s0m3.126s
WinNT (2000)0m39.439snot available0m22.904s

How do I start a persistent VM?

During development the bridge back end can be started with java -jar JavaBridge.jar SERVLET_LOCAL:port#. Unfortunately the simple servlet engine built into JavaBridge.jar is not very efficient. Please use some other servlet engine instead. The tomcat servlet engine for example contains scripts which allow you to start Java as a system service on Windows and Unix/Linux.

If you have compiled the C implementation, Apache or IIS can automatically start/stop the Java VM as a sub component. But in this setup the Java VM runs with the same (restricted) rights as the HTTP server, which may or may not be what you want. On Linux for example the VM is started by a RunJavaBridge executable as a child of the Apache main process. The Java VM runs as user apache/apache and uses the Security Enhanced Linux domain javabridge_t. It cannot access files such as /etc/passwd and it cannot open tcp sockets to other servers.

Unless you know how to pass options to child processes on Windows or Unix (see the java.wrapper option), and how set/change permissions (see chcon, chmod, chown), we recommend to start the PHP/Java Bridge via a servlet engine or J2EE server. -- You probably already have a servlet engine or J2EE server listening on 8080 or some other port, so that it might not be necessary to install a servlet engine or J2EE server to start the bridge back end.

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.