Menu

[r409]: / trunk / php-java-bridge / ABOUT.HTM  Maximize  Restore  History

Download this file

1113 lines (1062 with data), 43.5 kB

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
	<META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html">
	<TITLE>Integrate PHP & Java - PHP / Java Bridge</TITLE>
</HEAD>
<p>

</p> <BODY LANG="en-US" DIR="LTR"> <H1>What is the PHP/Java
Bridge?</H1> <P><FONT > The PHP/Java Bridge
  is an optimized XML protocol which can be used to connect a native script engine with a Java or <a href="http://www.ecma-international.org/publications/standards/Ecma-335.htm">ECMA 335</a> virtual machine. The <a href="documentation/PHP-API/html/java_8c.html">php java extension</a> uses this protocol to connect running PHP instances with already running Java or .NET <a href="server/documentation/API/overview-summary.html">backends</a>. The communication works in both directions, the <A HREF="http://www.jcp.org/aboutJava/communityprocess/edr/jsr223/">JSR 223</A> 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 frontend or the Java/.NET backend, if needed.

<p><FONT > 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.  </FONT></P>

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

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

<P><FONT > Unlike previous attempts (the <a href="http://www.php.net/manual/en/ref.java.php">ext/java</a> or the <A HREF="http://www.jcp.org/aboutJava/communityprocess/edr/jsr223/">JSR 223</A> sample
implementation) the PHP/Java Bridge does <em>not</em> use the java
native interface ("JNI"). Php instances are allocated from the HTTP
(Apache/IIS) pool, instances of java/j2ee components are allocated
from the backend. The allocated instances communicate using a
"continuation passing style", see <a
href="documentation/PHP-API/html/java_8c.html#a43"><code>java_closure()</code></a> and the <a href="server/documentation/API/php/java/bridge/Invocable.html">invocable interface</a>. In
case a php instance crashes, it will not take down the java
application server or servlet engine.  </FONT></P>

<H1>Motivation</H1>

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

<P><FONT > 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.  </FONT></P> <img src="tomcat-jsf.jpg"
align="right" vspace="0" hspace="0" name="php-jsf" alt="Apache/Tomcat
with PHP scripts and the Java Server Faces framework">

<P><FONT > 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.  </FONT></P>

<P><FONT >PHP and the PHP/Java Bridge might also be interesting for
java developers. There are a number of technologies based on the JSP
template system such as jakarta <a
href="http://struts.apache.org/">Struts</a> and its successor <a
href="http://www.jcp.org/en/jsr/detail?id=127">Java Server
Faces</a>. 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 templates while web developers can
create a prototype using php code and use the existing framework from
their code.</img>

</FONT></P> 
<p></p>
<H1>Description</H1>
<P><FONT > The bridge adds the following primitives to PHP.  The type
  mappings are shown in <a href="#type-mapping">table 1</a>.

<ul>
<li>
  <code>new <strong>Java</strong>("CLASSNAME")</code>: References and instanciates the class CLASSNAME.
 After script
     execution the referenced classes may be garbage collected. Example: <br><br>
     
<blockquote>
<code>
      &lt;?php<br>
$v = new Java("java.util.Vector");<br>
$v->add($buf=new Java("java.lang.StringBuffer"));<br>
$buf->append("100");<br>
echo (int)($v->elementAt(0)->toString()) + 2;<br>
      ?&gt;<br>
</code>
</blockquote>
<br>
<li>
  <code>new <strong>JavaClass</strong>("CLASSNAME")</code>: 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: <br><br>
     
<blockquote>
<code>
      $Object = new JavaClass("java.lang.Object");<br>
      $obj = $Object->newInstance();<br><br>
      $Thread = new JavaClass("java.lang.Thread");<br>
      $Thread->sleep(10);<br><br>
</code>
</blockquote>
<br>

<li>
  <code><strong>java_require</strong>("JAR1;JAR2")</code>: Makes additional libraries
     available to the current script.  JAR can either be  
     a "http:", "ftp:", "file:" or a "jar:" or a default <a href="#jar-location">location</a>. On &quot;Security Enhanced Linux&quot; (<a href="README">please see the README</a>) the <a href="#sel">location must be tagged</a> with a <em>lib_t</em> security context. Example: <br><br>
<blockquote>
<code>
// load scheme interpreter<br>
// try to load it from /usr/share/java/ or from sourceforge.net<br>
java_require("kawa.jar");<br>
java_require("http://php-java-bridge.sourceforge.net/kawa.jar");<br>
$n=100;<br>
$System = new JavaClass("java.lang.System");<br>
$t1 = $System->currentTimeMillis();<br>
$code="(letrec ((f (lambda(v) (if (= v 0) 1 (* (f (- v 1)) v))))) (f $n))";<br>
$scheme = new java("kawa.standard.Scheme");<br>
$res=(float)$scheme->eval($code);<br>
echo "${n}! => $res\n";<br>
$delta = $System->currentTimeMillis() - $t1;<br>
echo "Evaluated in $delta ms.\n";<br>
</code>
</blockquote>
<br>
<br>
<li>
  <code><strong>java_context()</strong></code>: Makes the <code>javax.script.ScriptContext</code>
     available to the current script. All implicit web objects (session, servlet context, etc.) are <a href="server/documentation/API/php/java/servlet/Context.html#getHttpServletRequest()">available from the context</a>, when the backend is running in a servlet engine or application server. The following example uses the jdk1.6 <code>jrunscript</code> to eval php statements interactively:  <br><br>
<blockquote>
<code>
/opt/jdk1.6/bin/jrunscript -l php-intractive<br>
php-interactive&gt; echo java_context()->getAttribute("javax.script.name"); <br>
=&gt; STDIN <br>
<br>
</code>
</blockquote>
<br>
<li>
  <code><strong>java_closure</strong>(ENVIRONMENT, MAP, TYPE)</code>: 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:<br><br><blockquote>
&lt;?php<br>
function toString() { return "hello" ; }<br>
echo (string)java_closure();<br>
?&gt;<br>
=&gt; hello
</blockquote>
<br><br>
Example which uses PHP and Mono:<br>
 <br><br>
<blockquote>
<code>
class GtkDemo {<br>
&nbsp;&nbsp;var $Application;<br>
<br>
&nbsp;&nbsp;function GtkDemo() {<br>
&nbsp;&nbsp;&nbsp;&nbsp;mono_require("gtk-sharp");	// link the gtk-sharp library<br>
&nbsp;&nbsp;}<br>
<br>
&nbsp;&nbsp;function delete($sender, $e) {<br>
&nbsp;&nbsp;&nbsp;&nbsp;echo "delete called\n";<br>
&nbsp;&nbsp;&nbsp;&nbsp;$this-&gt;Application-&gt;Quit();<br>
&nbsp;&nbsp;}<br>
&nbsp;&nbsp;function clicked($sender, $e) {<br>
&nbsp;&nbsp;&nbsp;&nbsp;echo "clicked\n";<br>
&nbsp;&nbsp;}<br>
&nbsp;&nbsp;function init() {<br>
&nbsp;&nbsp;&nbsp;&nbsp;$this-&gt;Application = $Application = new Mono("Gtk.Application");<br>
&nbsp;&nbsp;&nbsp;&nbsp;$Application-&gt;Init();<br>
<br>
&nbsp;&nbsp;&nbsp;&nbsp;$win = new Mono("Gtk.Window", "Hello");<br>
&nbsp;&nbsp;&nbsp;&nbsp;$win-&gt;add_DeleteEvent (<br>
			&nbsp;&nbsp; new Mono(<br>
				&nbsp;&nbsp;&nbsp;&nbsp;"GtkSharp.DeleteEventHandler", <br>
				&nbsp;&nbsp;&nbsp;&nbsp;mono_closure($this, "delete")));<br>
<br>
&nbsp;&nbsp;&nbsp;&nbsp;$btn = new Mono("Gtk.Button", "Click Me");<br>
<br>
&nbsp;&nbsp;&nbsp;&nbsp;$btn-&gt;add_Clicked(<br>
		&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;new Mono(<br>
			&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; "System.EventHandler",<br>
			&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; mono_closure($this, "clicked")));<br>
&nbsp;&nbsp;&nbsp;&nbsp;$win-&gt;Add($btn);<br>
&nbsp;&nbsp;&nbsp;&nbsp;$win-&gt;ShowAll();<br>
&nbsp;&nbsp;}<br>
<br>
&nbsp;&nbsp;function run() {<br>
&nbsp;&nbsp;&nbsp;&nbsp;$this-&gt;init();<br>
&nbsp;&nbsp;&nbsp;&nbsp;$this-&gt;Application-&gt;Run();<br>
&nbsp;&nbsp;}<br>
}<br>
<br&gt;<br>
$demo = new GtkDemo();<br>
$demo-&gt;run();<br>
</code>
</blockquote>

<br>
<li>
  <code>$session=<strong>java_session</strong>()</code>: Creates or retrieves a session context. When the backend is running in a J2EE environment, the session is taken from the request object, otherwise it is taken from PHP. Please see the  <a href="server/documentation/API/php/java/bridge/ISession.html">ISession interface documentation</a> for details. The <code>java_session()</code> must be called <a href="http://www.php.net/manual/en/function.headers-sent.php">before the response headers have been sent</a> and it should be called as the first statement within a php script.
<blockquote>
<code>
$session = java_session();<br>
$servletRequest = $session->getHttpServletRequest();<br>
$servletRequest->setAttribute(...);<br>
...<br>
</code>
</blockquote>
<br>
<li>

  <code>$session=<strong>java_session</strong>(SESSIONNAME)</code>:
Creates or retrieves the session <code>SESSIONNAME</code>. This
primitive uses a "private" session store with the name
SESSIONNAME. Please see the <a
href="server/documentation/API/php/java/bridge/ISession.html">ISession
interface documentation</a> for details. For java values
<code>$_SESSION['var']=val</code> is syntactic shugar for
<code>java_session(session_id())-&gt;put('var', val)</code>.
<blockquote>

<code>
$session=java_session("testSession");<br>
if($session->isNew()) {<br>
&nbsp;&nbsp;  echo "new session\n";<br>
&nbsp;&nbsp;  $session->put("a", 1);<br>
&nbsp;&nbsp;  $session->put("b", 5);<br>
} else {<br>
&nbsp;&nbsp;  echo "cont session\n";<br>
}<br>
$session->put("a", $session->get("a")+1);<br>
$session->put("b", $session->get("b")-1);<br>
<br>
$val=$session->get("a");<br>
echo "session var: $val\n";<br>
<br>
if($session->get("b")==0) $session->destroy();<br>
</code>
</blockquote>
The <strong><code>java_session</code></strong> primitive is meant for values which <em>must</em> survive the current script.  If you want to cache data which is expensive to create, bind the data to a class.  Example:
<blockquote>
<code>
// Compile this class, create cache.jar and copy it to /usr/share/java<br>
public class Cache {<br>
&nbsp;&nbsp; public static Cache instance = makeInstance();<br>
}<br><br>
&lt;?php<br>
java_require(&quot;cache.jar&quot;);<br>
$Cache = new JavaClass(&quot;Cache&quot;);<br>
$instance=$Cache->instance; //instance will stay in the VM until the VM runs short of memory<br>
?&gt;<br>
</code>
</blockquote>
<br>
  <li> <code><strong>JavaException</strong></code>: A java exception class. Available in PHP 5 and
    above only.  Example:<br><br>
<blockquote>
<code>
      try {<br>
       &nbsp;&nbsp;new java("java.lang.String", null);<br>
      } catch(JavaException $ex) {<br>
&nbsp;&nbsp;         $trace = new java("java.io.ByteArrayOutputStream");<br>
&nbsp;&nbsp;         $ex-&gt;printStackTrace(new java("java.io.PrintStream", $trace));<br>
&nbsp;&nbsp;         print "java stack trace: $trace\n";<br>
      }<br>

</code>
</blockquote>
<br>
  <li> <code>foreach(COLLECTION)</code>: 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:<br><br>
<blockquote>
<code>
     $conversion = new java("java.util.Properties");<br>
     $conversion->put("long", "java.lang.Byte java.lang.Short java.lang.Integer");<br>
     $conversion->put("boolean", "java.lang.Boolean");<br>
     foreach ($conversion as $key=>$value) <br>
&nbsp;&nbsp;     echo "$key => $value\n";<br>
</code>
</blockquote>
<br>
  <li> <code>[index]</code>: 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:<br><br>
<blockquote>
<code>
$Array = new JavaClass("java.lang.reflect.Array");<br>
$String = new JavaClass("java.lang.String");<br>
$entries = $Array->newInstance($String, 3);<br>
$entries[0] ="Jakob der L&uuml;gner, Jurek Becker 1937--1997";<br>
$entries[1] ="Mutmassungen &uuml;ber Jakob, Uwe Johnson, 1934--1984";<br>
$entries[2] ="Die Blechtrommel, G&uuml;nter Grass, 1927--";<br>
for ($i = 0; $i < $Array->getLength($entries); $i++) { <br>
&nbsp;&nbsp;  echo "$i: " . $entries[$i] ."\n";<br>
}<br>
</code>
</blockquote>
<br>
  <li> <code><strong>java_instanceof</strong>(JAVA_OBJ, JAVA_CLASS)</code>: Tests if JAVA_OBJ is an instance of JAVA_CLASS.  Example:<br><br>
<blockquote>
<code>
$Collection=new JavaClass("java.util.Collection");<br>
$list = new java("java.util.ArrayList");<br>
$list->add(0);<br>
$list->add(null);<br>
$list->add(new java("java.lang.Object"));<br>
$list->add(new java("java.util.ArrayList"));<br>
foreach ($list as $value) { <br>
&nbsp;&nbsp;  if($value instanceof java && java_instanceof($value, $Collection))<br>
&nbsp;&nbsp;&nbsp;&nbsp;      /* iterate through nested ArrayList */ <br>
&nbsp;&nbsp;  else<br>
&nbsp;&nbsp;&nbsp;&nbsp;      echo "$value\n";<br>
}
<br>
</code>
</blockquote>
<br>

  <li> <code>java_last_exception_get()</code>: Returns the last exception instance or
     null. Since PHP 5 you can use <code>try/catch</code> instead.<br><br>

  <li> <code>java_last_exception_clear()</code>: Clears the error condition.  Since PHP 5 you can use <code>try/catch</code> instead.
</ul>
<br>
<A NAME="type-mapping"></A>
<center>
<B
>Table 1. Type Mappings</B
></P
>
<TABLE
BORDER="1"
><COL><COL><COL><COL><THEAD
><TR
><TH
>PHP</TH
><TH
>Java</TH
><TH
>Description</TH
><TH
>Example</TH
></TR
></THEAD
><TBODY
><TR
><TD
>object</TD
><TD
>java.lang.Object</TD
><TD
>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 <a href="PROTOCOL.TXT">XML protocol</a>, see the <a href="examples/clients/README">python and scheme</a> examples).</TD
><TD
>$buf=new java("java.io.ByteArrayOutputStream");<br>
$outbuf=new java("java.io.PrintStream", $buf);<br>
</TD
></TR
><TR
><TD
>null</TD
><TD
>null</TD
><TD
>NULL value</TD
><TD
>$outbuf->println(null);</TD
></TR
><TR
><TD
>exact number</TD
><TD
>integer (default) or long, depending on the flag <a href="#ext_java_compatibility">java.ext_java_compatibility</a>.</TD
><TD
>64 bit data on protocol level, coerced to 32bit int/Integer or 64bit long/Long</TD
><TD
>$outbuf->println(100);<br>
</TD
></TR
></TR
><TR
><TD
>boolean</TD
><TD
>boolean</TD
><TD
>boolean value</TD
><TD
>
$outbuf->println(true);
</TD
></TR
><TR
><TD
>inexact number</TD
><TD
>double</TD
><TD
>IEEE floating point</TD
><TD
>$outbuf->println(3.14);
</TD
></TR
><TR
><TD
>string</TD
><TD
>byte[]</TD
><TD
>binary data, unconverted</TD
><TD
>$bytes=$buf->toByteArray();</TD
></TR
><TR
><TD
>string</TD
><TD
>java.lang.String</TD
><TD
>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 <strong><code>java_set_file_encoding()</code></strong> primitive.</TD
><TD
>$string=$buf->toString();</TD
><TR
><TD
>array (as array)</TD
><TD
>java.util.Collection or T[]</TD
><TD
>PHP4 sends and receives arrays as values.  PHP5 sends arrays as values and receives object handles which implement the new iterator and array interface.</TD
><TD
>// pass a Collection to Vector<br>
$ar=array(1, 2, 3);<br>
$v=new java("java.util.Vector", $ar);<br>
echo $v->capacity();<br><br>
// pass T[] to asList()<br>
$A=new JavaClass("java.util.Arrays");<br>
$lst=$A->asList($ar);<br>
echo $lst->size();
</TD
><TR
><TD
>array (as hash)</TD
><TD
>java.util.Map</TD
><TD
>PHP4 sends and receives hashtables as values.  PHP5 sends hashtables as values and receives object handles which implement the new iterator interface.</TD
><TD
>$h=array("k"=>"v", "k2"=>"v2");<br>
$m=new java("java.util.HashMap",$h);<br>
echo $m->size();
</TD
><TR
><TD
>JavaException</TD
><TD
>java.lang.Exception</TD
><TD
>A wrapped exception class. The original exception can be retrieved with $exception->getCause();</TD
><TD
>...<br>catch(JavaException $ex) { <br>
echo $ex->getCause();<br>
} </TD
></TR
></TBODY
></TABLE
>
</center>
<br><br>
  There is one example provided: test.php.  You can either invoke the
  test.php by typing ./test.php or copy the example into the document
  root of you web-server and evaluate the file using the browser.

</FONT></P>
<P><FONT >
<a name="jar-location">
  Custom java libraries (.jar files) can be stored in the following
  locations:

<ol>
<li>
    Somewhere on a HTTP or FTP server, see PHP function
      java_require. <a name="sel">
On Security Enhanced Linux <code>.jar</code> files can only be loaded from locations which are tagged with the <em>lib_t</em> security context.

   <li> 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 <em>lib_t</em> security context.

   <li> In the <code>/usr/share/java/</code> directory, if it exists and is accessible
      when the JVM starts the bridge. On Security Enhanced Linux this directory is tagged with the <em>lib_t</em> security context.
</ol>
</FONT></P>
</P>
</a></a>
<P><FONT > The PHP/Java Bridge can operate in 4 different modes: <ol>
  <li> 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 backend (Java or .NET VM) for
  each request. But it does not require any administrative privileges.

   <li> Permanently activated in the global php.ini file with an
 internal java process running in the HTTP server domain.  In this
 mode the bridge backend starts when the HTTP server starts and terminates
 when the HTTP server terminates. Recommended during
 development. Please see <a href="#mode2">web server installation
 below</a>.

   <li> Permanently activated in the global php.ini file with an
      external java process.  Recommended for <a
      href="#mode3">production systems</a>.  This mode is used by the
      RPM package available for RedHat Enterprise Linux.  In this mode
      the bridge starts and stops as a system service.

   <li> Permanently activated in the global php.ini file with an
      external <a href="#mode4">application server or servlet engine</a>.
      PHP be can run as a CGI sub-component within a pure java application server or be installed as a Apache/IIS module. 

</ol>
<P><FONT > Furthermore the PHP/Java Bridge can be: <ul> <li> 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. 

   <li> Compiled with the GNU Java library.  You can either start GNU
      Java as a separate process (just like a "real" Java VM) or
      compile everything into a PHP binary.  This should only be
      necessary if there is no official JRE available for the OS or one
      doesn't want to ship a JRE with the product. 

   <li> Compiled with Novell's MONO (a ".NET" clone).  This is
 available as a separate download.  </ul>

</FONT></P>
<P STYLE="margin-top: 0.42cm; page-break-after: avoid"><BR><BR>
</P>
<H1>Installation
instructions</H1>
<P STYLE="margin-top: 0.42cm; page-break-after: avoid"><FONT ><FONT SIZE=3>If
you have a RedHat Linux system (RedHat Enterprise or
Fedora), you can download the 32bit RPM and type <code>rpm -i
php-java-bridge-v.x.y-1-i386.rpm php-java-bridge-standalone-v.x.y-1-i386.rpm</code> to install it (if you run a 64bit system <strong>and</strong> a 64bit JVM you need to install the 64bit RPM instead). For other operating systems please follow 
the instructions below (on Security Enhanced Linux please use the RPM or please read the README before installation).</FONT></FONT></P>
<UL>
	<LI><P><FONT >Make sure you
	have java version 1.4.2 or higher, gcc 3.2 or higher, apache 1.3 or
	higher, <em>autoconf </em> 2.57 or higher, <em>libtool</em> 1.4.3 or higher, <em>automake</em> 1.6.3 or higher, GNU make and php 4.3.2 or higher
	installed. You can check the version numbers with the commands <code>java
	-version</code>, <code>gcc --version</code>, <code>apachectl -version</code>, <code>libtool --version</code>, <code>automake --version</code>, <code>make null --version</code>, <code>autoconf --version</code> and
	<code>php-config --version</code>.
	</P>
	<LI><P><FONT ><FONT >Download
	the source code of the bridge from
	</FONT><A HREF="http://www.sourceforge.net/projects/php-java-bridge"><FONT >http://www.sourceforge.net/projects/php-java-bridge</FONT></A></FONT></P>
	<LI><P><FONT >Extract the file
	with the command: <code>cat php-java-bridge_v.x.y.tar.bz2 | bunzip2 |
	tar xf -</code></FONT></P>
	<LI><P STYLE="font-style: normal"><FONT >In
	the directory php-java-bridge-v.x.y build the module: 
<BR><BR><code>phpize &amp;&amp; ./configure
	--with-java=/usr/java/default &amp;&amp; make </code></FONT></P>
	<LI><P STYLE="font-style: normal"><FONT >Then
	install the module as root. Type:<BR><BR><code>su -c 'sh
	install.sh'<BR>&lt;enter password&gt;</code></FONT></P>
	<LI><P STYLE="font-style: normal"><FONT ><A name="mode2">The PHP/Java Bridge can be run as a <strong>sub-component of the web server</strong>; add the following lines
	to the <code>php.ini</code>. Or add a file <code>java.ini</code> to the directory that contains
	the php module descriptions (usually <code>/etc/php.d/</code>) with the following
	content:<BR><BR><code>extension = java.so<BR>[java]</code></FONT></A></P>
	<LI><P STYLE="font-style: normal"><FONT >Restart
	the apache service with the command: <code>apachectl restart</code></FONT></P>
	<LI><P><FONT >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 backend automatically starts or re-starts whenever you start or re-start the web-server.
	</P>
	<LI><P><FONT ><A name="mode3">In a <strong>production environment</strong> it is recommended to separate the java VM and the HTTP process by setting the communication channel. The <code>java.socketname</code> should be set to the name of the socket, it will be created if it doesn't exist.  The java section of the php <code>.ini</code> file should contain a <code>java.socketname</code> option. The following is an example from RedHat Enterprise Linux and Fedora:
<BR><BR><code>extension = java.so<BR>[java]<BR>java.socketname="/var/run/.php-java-bridge_socket"</code><br><br>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, <code>php-java-bridge.service</code>, which can be used to start/stop the PHP/Java Bridge backend as system service. All available <code>.ini</code> options are listed in <a href="#ini-options">table 2</a>.</A> </FONT>

	</P>
	<LI><P><FONT ><A name="mode4">In a production environment which requires <strong>load balancing and failover</strong> or <strong>session sharing between PHP, JSP and Servlets</strong> it is recommended deploy the backend into a servlet engine or an application server; tomcat 5 for example. Disable the <code>java.socketname</code>, either a) enable the <code>java.hosts</code> and <code>java.servlet</code> options or b), if you don't have Apache or IIS, install PHP as a CGI/FastCGI binary so that your application server can find it and start the application server. The <code>.ini</code> file should contain:
<BR><BR><code>extension = java.so<BR>[java]<br>
java.hosts=&quot;127.0.0.1:8080&quot<br>
java.servlet=On
</code>
<br><br>

</A> </FONT>

	</P>
</UL>
<A NAME="ini-options"></A>
<center>
<B
>Table 2. <code>.ini</code> options</B
></P
>
<TABLE
BORDER="1"
><COL><COL><COL><COL><THEAD
><TR
><TH
>Name</TH
><TH
>Default</TH
><TH
>Description</TH
><TH
>Example</TH
></TR
></THEAD
><TBODY
><TR
><TD
>java.java_home</TD
><TD
>compile time option.</TD
><TD
>The java installation directory.</TD
><TD
>java.java_home="/opt/jdk1.5"</TD
></TR
><TR
><TD
>java.java</TD
><TD
>compile time option.</TD
><TD
>The java executable.</TD
><TD
>java.java="/opt/jdk1.5/jre/bin/java"
</TD
></TR
><TR
><TD
>java.socketname</TD
><TD
>/var/run/.php-java-bridge_socket</TD
><TD
>The name of the communication channel for the local backend. Must be an integer, if a secure "unix domain" channel is not available (Windows, Mac OSX).</TD
><TD
>java.socketname="9167"
</TD
></TR
><TR
><TD
>java.log_level</TD
><TD
>1</TD
><TD
>The log level from 0 (log off) to 4 (log debug).</TD
><TD
>java.log_level="3"</TD
></TR
><TR
><TD
>java.log_file</TD
><TD
>/var/log/php-java-bridge.log</TD
><TD
>The log file for the local PHP/Java Bridge backend.</TD
><TD
>java.log_file="/tmp/php-java-bridge.log"</TD
><TR
><TD
>java.hosts</TD
><TD
>&lt;none&gt;</TD
><TD
>Additional bridge hosts which are used when the local backend is not available.</TD
><TD
>java.hosts="127.0.0.1:9168;127.0.0.1:9169"
</TD
><TR
><TD
>java.servlet</TD
><TD
>Off</TD
><TD
>The communication protocol. If set to <code>On</code> or to <code>User</code>, the bridge uses HTTP to communicate with the <code>java.hosts</code> backends. The option <code>User</code> preserves the context, <code>On</code> is for backward compatibility and rewrites the context to: <code>/JavaBridge/JavaBridge.php</code>.</TD
><TD
><code>;; Make sure that this option is only set <br>;; if your backend 
is deployed in a<br>;; servlet engine or application server.</code><br>
java.servlet=User<br>
</TD
><TR
><TD
>java.classpath</TD
><TD
> compile time option.</TD
><TD
>The java classpath. <em>Please do not change the default value</code></TD
><TD
>java.classpath="/tmp/myJavaBridge.jar:/tmp/myCasses/"<br>
</TD
></TR
><TR
><TD
>java.libpath</TD
><TD
>compile time option.</TD
><TD
>The directory which contains the <code>natcJavaBridge.so</code> used for local ("unix domain") sockets. <em>Please do not change the default value.</em></TD
><TD
>
java.libpath="/tmp/"
</TD
></TR
><TR
><TD
><A name="ext_java_compatibility">java.ext_java_compatibility</A></TD
><TD
>Off</TD
><TD
>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. <em>Leave it off, if possible</em>.</TD
><TD
>
java.ext_java_compatibility=On
</TD
></TR
></TBODY
></TABLE
>
</center>
<br><br>
<P><FONT >For further
information please read the <a href="README">README</a>, <a href="INSTALL">INSTALL</a>, <a href="INSTALL.LINUX">INSTALL.LINUX</a>, <a href="INSTALL.J2EE">INSTALL.J2EE</a> and <a href="INSTALL.WINDOWS">INSTALL.WINDOWS</a> documents contained in
the download files.</p>
<p>The <a href="NEWS">NEWS</a> file lists the latest user visible changes, development documentation can be found in the <a href="documentation/PHP-API/html/java_8c.html"><code>documentation</code></a> and <a href="server/documentation/API/overview-summary.html"><code>server/documentation</code></a> folder.

</FONT></P>
<P><BR><BR>
</P>

</P> <H1>FAQ</H1> <P><FONT > <ul> <li><H4>The bridge doesn't compile
on my system!?!</H4> <p>Please follow the instructions from the
<a href="INSTALL">INSTALL document</a> as close as possible. In particular the backend needs the specified versions of <em>autoconf</em>, <em>libtool</em> and <em>automake</em> in the path. Backend compilation can be switched off with the <code>--disable-backend</code> configure option. A compiled, platform-independent backend ("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 <em>not</em> report this problem to the
mailing list. Please <a
href="http://sourceforge.net/tracker/?func=add&group_id=117793&atid=679233">open
a problem report instead</a> (you don't need an account to submit a
problem report).</p> <p>On RPM based Security Enhanced Linux
installations (RHEL, Fedora) please install one of the binary RPM's or
compile a binary RPM from the source RPM using the command:
<code>rpmbuild --rebuild php-java-bridge*src.rpm</code></p> <p>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 <code>lib/php</code>
directory to <code>/usr/lib/php</code> and restart apache.</p> 

<li> <H4>Can I use java libraries without
installing java?</H4> <p>Yes. Simply ommit the
<code>--with-java=</code> configure option. The bridge will use the
<code>libgcj</code> 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.</p> <li> <H4>Does the
bridge run native code within my servlet engine or application
server?</H4> <p>No. The bridge backend 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.</p> <li> <H4>How do I make my script state (objects or
variables) persistent?</H4> <p>If you must code it yourself: with
e.g. <code>java_session()->put("buf", $stringBuffer)</code> or via
<code>$_SESSION["buf"]=$stringBuffer</code>. The
<code>$_SESSION</code> is syntactic shugar provided by the <a
href="http://www.php.net/manual/en/ref.session.php">php session
module</a>, it uses <code><a
href="documentation/PHP-API/html/java_8c.html#a34">java_session()<a></code>
internaly. If you don't want depend on the php session module, for
example if you have compiled php without the <code>session.so</code>,
use java_session() instead.</p> <p> If you use the <a
href="http://www.jcp.org/en/jsr/detail?id=127">Java Server Faces</a>
framework, you declare the scope of the script in the <a
href="server/WEB-INF/faces-config.xml">php
managed bean descriptor<a>. For example if the
<code>managed-bean-scope</code> is changed from <code>request</code>
to <code>session</code>, 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.</p> <li> <H4>How many threads
does the bridge start?</H4> <p>Request-handling threads are started
from a thread pool, which limits the number of user requests to 20
(default), see system property
<code>php.java.bridge.threads</code>. All further requests have to
wait until one of the worker threads returns to the pool. <p> <p>When
running in a servlet engine, a <a
href="server/documentation/API/php/java/bridge/http/ContextServer.html">ContextServer</a>
is started which handles the pipe or local socket communication
channel.  </p> <p>When java invokes local scripts outside of a HTTP
environment, the bridge starts a <a
href="server/documentation/API/php/java/bridge/http/HttpServer.html">HttpServer</a>,
a <a
href="server/documentation/API/php/java/bridge/http/ContextServer.html">ContextServer</a>
and a <a
href="server/documentation/API/php/java/script/HttpProxy.html">HttpProxy</a>. The
HttpProxy represents the php continuation and the HttpServer the
request-handling java continuation associated with the JSR223 script.
</p> 

<li> <H4>How do I lock down the VM so that users cannot start
threads or call System.exit?</H4> <p>Usually with a java policy
file. An example file will ship with version 3.0.9. </p> 

<li> <H4>Where is my output?</H4> <p><code>System.out</code> and <code>System.err</code> 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 backend the output appears in the <code>/var/log/php-java-bridge.log</code> or in JavaBridge.log, see .ini option <code>java.log_file</code>. For the j2ee backend the location of the log file(s) depends on the j2ee server configuration.</p> 

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

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

<li> <H4>How fast is it?</H4> <p> 
The following scripts were
executed on one 1.688 GHZ x86 cpu running RedHat Fedora Core 4 Linux and Sun jdk1.6.0:
</p>
The PHP 5.1.2 code<br>
<p>
<code>
&lt;?php<br>
$String = new JavaClass("java.lang.String");<br>
$buf=new java("java.lang.StringBuffer");<br>
<br>
$i=0;<br>
java_begin_document();<br>
while($i&lt;400000) {<br>
&nbsp;&nbsp;&nbsp;&nbsp;$i=$i+1;<br>
&nbsp;&nbsp;&nbsp;&nbsp;$buf-&gt;append(new java("java.lang.String", $String-&gt;valueOf($i)));<br>
}<br>
java_end_document();<br>
<br>
print $buf-&gt;length() . "\n";<br>
?&gt;<br>
</code>
</p>
The jython 2.1 code<br>
<p>
<code>
from java import lang<br>
<br>
buf = lang.StringBuffer();<br>
i=0<br>
while i<400000:<br>
&nbsp;&nbsp;&nbsp;&nbsp;i=i+1<br>
&nbsp;&nbsp;&nbsp;&nbsp;buf.append(lang.String(lang.String.valueOf(i)));<br>
<br>
print buf.length();<br>
</code>
</p>
The ECMAScript ("Mozilla Rhino") code<br>
<p>
<code>
buf = new java.lang.StringBuffer();<br>
for(i=0; i<400000; i++) buf.append(new String(i));<br>
print (buf.toString().length());<br>
</code>
</p>
<p>
<center>
<TABLE
BORDER="1"
><COL><COL><COL><COL><THEAD
><TR
><TH
>Command</TH
><TH
>Script Engine</TH
><TH
>Communication Channel</TH
><TH
>Execution time (real, user, sys)</TH
></TR
></THEAD

<TBODY
><TR
><TD
>time jrunscript -l php t11.php</TD
><TD
>PHP5 + PHP/Java Bridge 3.0.8</TD
><TD
>named pipes</TD
><TD
>0m20.112s,<br>
0m18.999s,<br>
0m0.651s
</TD
></TR
>
<TBODY
><TR
><TD
>java -jar JavaBridge.jar INET:9967 & time php t11.php</TD
><TD
>PHP5 + PHP/Java Bridge 3.0.8</TD
><TD
>TCP Sockets, client and server running on the same CPU</TD
><TD
>0m22.407s,<br>
0m9.848s,<br>
0m0.145s
</TD
></TR
>
<TBODY
><TR
><TD
>java -jar JavaBridge.jar INET:9967 & time php t11.php</TD
><TD
>PHP5 + PHP/Java Bridge 3.0.8</TD
><TD
>TCP Sockets, client and server running on different machines</TD
><TD
>0m31.507s,<br>
0m26.460s,<br>
0m3.567s
</TD
></TR
>

<TBODY
><TR
><TD
>time jrunscript -J-Xmx512M -J-Xms512M -l js t11.js</TD
><TD
>ECMA script</TD
><TD
>none (native code)</TD
><TD
>1m36.877s,<br>
0m55.398s,<br>
0m0.323s
</TD
></TR
>
<TBODY
><TR
><TD
>time java -classpath jython.jar org.python.util.jython t11.py</TD
><TD
>Jython 2.1</TD
><TD
>none (native code)</TD
><TD
>0m6.725s,<br>
0m6.551s,<br>
0m0.107s
</TD
></TR
>

</TABLE
>
</center>
</p>
<p>
</p>
<li> <H4>How do I start a persistent VM?</H4> 
<p>
If you want to start <em>one persistent VM per HTTP server</em> running on a computer, see 
the <a href="#mode2">web server installation</a> description. 
If you want to start <em>one persistent VM per computer</em>, please see <a href="#mode3">Linux RPM package</a> or the <a href="#mode4">application server or servlet engine</a> description.
</p>
<p>Furthermore it is possible to start standalone backend, for example with the command:<br><br>
<code>
&nbsp;&nbsp;java -jar JavaBridge.jar INET_LOCAL:9676 3<br>
</code>
<br>
The <code>php.ini</code> entry might look like:<br><br>
<code>
&nbsp;&nbsp;[java]<br>
&nbsp;&nbsp;java.hosts = 127.0.0.1:9676<br>
&nbsp;&nbsp;java.servlet = Off<br>
</code>
<br>
Please see the <a href="server/documentation/API/php/java/bridge/JavaBridge.html">JavaBridge</a> documentation for details.
</p>

<li> <H4>I want to start the backend 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?</H4> 
<p>
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: <code>java -Djava.library.path=...  -Djava.class.path=... -Djava.awt.headless=true php.java.bridge.JavaBridge SOCKET_NAME LOG_LEVEL LOG_FILE</code>.
A custom wrapper can be set with:<br><br>
<code>
java.wrapper=/path/to/wrapper/binary<br>
</code>
</p>
<p>
On Unix the bridge terminates the sub-process hierarchy with <code>SIGTERM</code>, sleep 5 seconds and <code>SIGTERM</code>, if necessary, sleep 5 seconds and <code>SIGKILL</code>, 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 <code>cmd /c</code> wrapper.
</p>
<p>
Please see the <code>JavaWrapper</code> from the  RedHat <code>php-java-bridge-standalone</code> RPM for an example.
</p>
<li> <H4>I want to use the bridge as a replacement for the <a href="http://www.php.net/manual/sl/ref.java.php#java.servlet">PHP 4 servlet API</a>, how do I install it into tomcat?</H4> 
<p>
Download the J2EE binary and copy the <code>JavaBridge.war</code> into the tomcat <code>webapps</code> folder. After that visit <code>http://localhost:8080/JavaBridge</code> and run the supplied php examples.
Please see <code>webapps/JavaBridge/WEB-INF/cgi/README</code> for details.
</p>
<li> <H4>How does the bridge handle OutOfMemoryErrors?</H4> 
<p>
OutOfMemoryErrors may happen because a cached variable cannot be released, either because <p>
<ol>
<li> the variable is permanently referenced by a request-handling thread or
<li> the variable has been entered into the session or application store or 
<li> the variable is referenced by a thread outside of the scope of the PHP/Java Bridge.
</ol>
</p>
</p>
<p>When a <code>java.lang.OutOfMemoryError</code> reaches the request-handling thread, the PHP/Java Bridge thread pool removes the thread from its pool and writes a message <code>FATAL: OutOfMemoryError</code> to the PHP/Java Bridge log file. The session store is cleaned and all client connections are terminated without confirmation.
</p>
<p>
If the OutOfMemoryError persists, this means that a thread outside of the PHP/Java Bridge has caused this error condition.
</p>
<p>
The following code example could cause an OutOfMemoryError:<br><br>
<code>
&lt;?php<br>
session_start();<br>
if(!$_SESSION["buffer"]) $_SESSION["buffer"]=new java("java.lang.StringBuffer");<br>
$_SESSION["buffer"]->append(...);<br>
?&gt;
</code>
</p>
<p>
OutOfMemory conditions can be debugged by running the backend with e.g.:<br><br>
<code>
java -agentlib:hprof=heap=sites -jar JavaBridge.jar<br>
</code>
</p>

<li> <H4>How do I retrieve the values from a java object?</H4>
<p>
With <code>java_values()</code> or with <code>settype</code>. Examples:
</p>
<p>
<code>
$str = new java("java.lang.String", "hello");
echo $str;<br>
=&gt; [o(String):"hello"]<br>
<br>
echo (java_values($str));<br>
=&gt; hello<br><br>
<br>
print_r (java_values($str->toCharArray()));<br>
=&gt; array('h', 'e', 'l', 'l', 'o')<br>
<br>
settype($str, "string");
echo $str;<br>
=&gt; hello<br>
<br>
$vector = new java("java.util.Vector", array("foo"=>1,"bar"=>2));<br>
settype($vector, "array");
print_r ($vector);<br>
=&gt; array(foo=>1, bar=>2)<br>
<br>
settype($vector, "object");
echo $vector->bar;<br>
=&gt; 2<br>
</p>
</ul>

</FONT></P> <H1>Related</H1> <P><FONT > <ul> <li> <a
href="http://www.eclipse.org/proposals/php-ide/">A PHP IDE</a>.  <li>
<a href="http://zez.org/article/articleview/26/">A tutorial how to use
the predecessor &quot;ext/java&quot;</a>.  <li> <a
href="http://www.caucho.com/resin-3.0/php/index.xtp">A commercial free
(GPL) PHP engine written in pure java</a>.  <li> <a
href="http://www.zend.com/store/products/zend-platform/java.php">A
commercial non-free bridge which uses the same technology as the
PHP/Java Bridge</a>.  <li> <a
href="http://www.devx.com/Java/Article/21707">Calling Enterprise Java
Beans from PHP/SOAP</a>.  <li> <a
href="examples/j2ee/README">Calling
Enterprise Java Beans from the PHP/Java Bridge</a>.  </ul> </FONT></P>

</BODY>
</HTML>
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.