Menu

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

Download this file

1496 lines (1447 with data), 66.4 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-based network 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. It is more than 50 times faster than local RPC via SOAP, uses less resources on the web-server side and it is faster and more reliable than a communication via the Java Native Interface.</p>
<p>
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">back-ends</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 front-end or the Java/.NET back-end, 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
back-end is running inside a ECMA compliant VM, for example Novell's
MONO or Microsoft's .NET.  Special features such as varargs,
reflection or assembly loading are also supported.  </FONT></P>

<P><FONT > When the back-end is running in a J2EE environment, session
sharing between PHP and JSP is always possible. Clustering and load
balancing is available <a href="http://www.onjava.com/pub/a/onjava/2004/03/31/clustering.html">when the J2EE environment supports these
features.</a>  </FONT></P>

<P><FONT >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 back-end. The allocated instances communicate using a
"continuation passing style", see <a
href="documentation/PHP-API/html/java_8c.html#a32"><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>
<H2>J2EE as a standard framework for PHP scripts</H2>
<P><FONT ><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">All PHP components are essentially transient. For complex
applications it is usually necessary to introduce "middleware" components
such as (enterprise-) "java beans" or enterprise applications which
provide caching, connection pooling or the "business logic" for the
pages generated by the PHP components. Parsing XML files for example
is an expensive task and it might be necessary to cache the generated
graph. Establishing connections to databases is an expensive operation
so that it might be necessary to re-use used connections. The standard
PHP XML or DB abstractions are useless in this area because they
cannot rely on a middle tier to do caching or db connection pooling.
</FONT></P>
<H2>Platform independence</H2>
<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>
<H2>A standard distribution format</H2>
<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>
<H2>Migration from JSP to PHP</H2>
<P><FONT >PHP and the PHP/Java Bridge might also be interesting for
Java developers. Although JSP is still used by frameworks 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>, JSP is <a href="http://www.onjava.com/pub/a/onjava/2004/06/09/jsf.html?page=1">not</a> a <a href="http://www.php.net">sucessful technology</a>. The main problem with JSP is that it requires a development tool at run-time, a "compiler", which makes deployment difficult and may generate error messages which are very difficult to understand, because they refer to an intermediate representation which has nothing to do with the original JSP file. For example if the configuration changes, it may happen that users are confronted with compiler error codes or run-time messages like "NullPointerException in __jsp" instead of proper error messages from the program. Since PHP/Java Bridge version 3.0 it is possible to embed
php scripts into the JSF framework, so that UI developers can
concentrate on developing HTML or XML templates while web developers can
create prototypes using PHP code and use the existing framework from
their code.</img>

</FONT></P> 
<p></p>
<H1>Overview</H1>
<P><FONT > The PHP/Java Bridge download contains an extension module for PHP versions >= 4.3.2 and a set of optional, auto-generated <a href="#proxies">PHP classes</a>. When the bridge has been configured to run without an external back-end, no Java, .NET or Mono is necessary;  popular Java libraries such as <code>lucene.jar</code> or <code>itext.jar</code> can be <a href="README.GNU_JAVA">interpreted by the bridge code</a> without using a Java SDK or Java JRE.
</p>
<p>
When the bridge has been configured to run with an external back-end, three back-ends are available: a "standalone back-end" called <code>JavaBridge.jar</code>, a J2EE back-end and Servlet SAPI <code>JavaBridge.war</code> and a Mono/.NET back-end called <code>MonoBridge.exe</code>.
</p>
<p> 
To access Java libraries from PHP the following is necessary:
<ol>
<li> the extension module and the optional back-end should be installed in the PHP <code>extension_dir</code> directory. For example if the bridge has been configured to use the standalone back-end on Unix/Linux, the files <code>java.so</code> and <code>JavaBridge.jar</code> should be copied to the PHP <code>extension_dir</code>
<li>  a PHP <code>.ini</code> entry is necessary to activate the extension. For example the following line in the global php.ini file activates the extension on Unix/Linux:
<code> extension=java.so </code>
</ol>
</p>
<p><a name="proxies">It is recommended, although not required, to create PHP classes from the Java libraries and to install them into the PHP PEAR <code>include_path</code>.</a> For example the following command translates the Java library <code>lucene.jar</code> into PHP classes and installs them into the <code>/usr/share/pear/lucene</code> directory: 
<blockquote>
<code>java -jar JavaBridge.jar --convert /usr/share/pear lucene.jar</code>
</blockquote>
The Java libraries can be accessed by including the PHP classes once. PHP code can call all public Java methods or procedures and examine all public fields. All public PHP procedures can be called from Java, all PHP classes may implement Java interfaces and PHP objects may be passed to Java procedures or methods. Example:
<blockquote>
<code>
&lt;?php<br>
require_once("lucene/org_apache_lucene_search_IndexSearcher.php");<br>
require_once("lucene/org_apache_lucene_search_PhraseQuery.php");<br>
require_once("lucene/org_apache_lucene_index_Term.php");<br>
<br>
$searcher = new org_apache_lucene_search_IndexSearcher(getcwd());<br>
$term = new org_apache_lucene_index_Term("name", "test.php");<br>
$phrase = new org_apache_lucene_search_PhraseQuery();<br>
<br>
$phrase->add($term);<br>
<br>
$hits = $searcher->search($phrase);<br>
$iter = $hits->iterator();<br>
<br>
while($iter->hasNext()) {<br>
&nbsp;&nbsp;$next = $iter->next();<br>
&nbsp;&nbsp;$name = $next->get("name");<br>
&nbsp;&nbsp;echo "found name: $name\n";<br>
}<br>
?&gt;
</code>
</blockquote>
</p>
<p>
Java knowledge is not necessary and it is neither necessary nor recommended to write custom- or glue logic in the Java programming language. 
</p>
<p>The following sections describe the low-level Java interface. It can be used to create dynamic PHP proxies or PHP/Java Bridge bindings for other languages such as Perl or Python.
</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><a href="documentation/PHP-API/html/java_8c.html#a54">Java</a></strong>("CLASSNAME")</code>: References and instantiates 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><a href="documentation/PHP-API/html/java_8c.html#a55">JavaClass</a></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><a href="documentation/PHP-API/html/java_8c.html#a23">java_require</a></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>
<code>
// load scheme interpreter<br>
// try to load it from /usr/share/java/ or from sourceforge.net<br>
try { java_require("kawa.jar"); } catch (JavaException $e) {/*ignore*/}<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>
<br>
<br>
<li>
  <code><strong><a href="documentation/PHP-API/html/java_8c.html#a26">java_context</a></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>, if the back-end is running in a servlet engine or application server. The following example uses the jdk1.6 <a href="http://java.sun.com/javase/6/docs/tooldocs/share/jrunscript.html"><code>jrunscript</code></a> to eval PHP statements interactively:  <br><br>
<code>
/opt/jdk1.6/bin/jrunscript -l php-intractive<br>
php-interactive&gt; echo (string)(java_context()->getAttribute("javax.script.filename")); <br>
=&gt; &lt;STDIN&gt; <br>
<br>
</code>
<br>
<li>
  <code><strong><a href="documentation/PHP-API/html/java_8c.html#a31">java_values</a></strong>(JAVA_OBJECT)</code>: Fetches the values for <code>JAVA_OBJECT</code>, if possible. Examples:<br><br><blockquote>
<code>
$str = new java("java.lang.String", "hello");
echo $str;<br>
=&gt; [o(String):"hello"]<br>
<br>
// fetch the php string from the java string<br>
echo (java_values($str));<br>
=&gt; hello<br>
<br>
// fetch the values of the java char array<br>
print_r (java_values($str->toCharArray()));<br>
=&gt; array('h', 'e', 'l', 'l', 'o')<br>
<br>
// no php type exists for java.lang.Object<br>
print (java_values(new java("java.lang.Object")));<br>
=&gt; [o(Object):"java.lang.Object@4a85fc"]
</code>
</blockquote>
<br>
<li>
  <code><strong><a href="documentation/PHP-API/html/java_8c.html#a29">java_begin_document</a></strong>()</code> and <code><strong><a href="documentation/PHP-API/html/java_8c.html#a30">java_end_document</a></strong>()</code>: Enables/disables XML stream mode. In XML stream mode the PHP/Java Bridge XML statements are sent in one XML stream. Compared with SOAP, which usually creates the entire XML document before sending it, this mode uses much less resources on the web-server side. Raised server-side exceptions are reported when <code>java_end_document()</code> is invoked. Example:<br><br><blockquote>
<code>
// send the following XML statements in one stream<br>
java_begin_document();<br>
for ($x = 0; $x < $dx; $x++) {<br>
&nbsp;&nbsp;$row = $sheet->createRow($x);<br>
&nbsp;&nbsp;for ($y = 0; $y < $dy; $y++) {<br>
&nbsp;&nbsp;&nbsp;&nbsp;$cell = $row->createCell($y);<br>
&nbsp;&nbsp;&nbsp;&nbsp;$cell->setCellValue("$x . $y");<br>
&nbsp;&nbsp;&nbsp;&nbsp;$cell->setCellStyle($style);<br>
&nbsp;&nbsp;}<br>
}<br>
java_end_document(); // back to synchronous mode<br>
</code>
</blockquote>
<br>
<li>
  <code><strong><a href="documentation/PHP-API/html/java_8c.html#a32">java_closure</a></strong>(ENVIRONMENT, MAP, TYPE)</code>: Makes it possible to call PHP code from Java.  It closes over the PHP environment, packages it up as a java class and returns an instance of the 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>
<code>
&lt;?php<br>
function toString() { return "hello" ; }<br>
echo (string)java_closure();<br>
?&gt;<br>
=&gt; hello
</code>
</blockquote>
<br>
<li>
  <code>$session=<strong><a href="documentation/PHP-API/html/java_8c.html#a25">java_session</a></strong>()</code>: Creates or retrieves a session context. When the back-end is running in a J2EE environment, the session is taken from the request object, otherwise it is taken from PHP. Please see the  <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();<Mr>
$servletRequest = $session->getHttpServletRequest();<br>
$servletRequest->setAttribute(...);<br>
...<br>
</code>
</blockquote>
<br>
<li>

  <code>$session=<strong><a href="documentation/PHP-API/html/java_8c.html#a25">java_session</a></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 sugar 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><a href="documentation/PHP-API/html/java_8c.html#a54">JavaException</a></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><a href="documentation/PHP-API/html/java_8c.html#a24">java_instanceof</a></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><a href="documentation/PHP-API/html/java_8c.html#a20">java_last_exception_get</a>()</code>: Returns the last exception instance or
     null. Since PHP 5 you can use <code>try/catch</code> instead.<br><br>

  <li> <code><a href="documentation/PHP-API/html/java_8c.html#a21">java_last_exception_clear</a>()</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 hash-tables as values.  PHP5 sends hash-tables 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 your 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
      <a href="documentation/PHP-API/html/java_8c.html#a23">java_require</a>. <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 5 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 back-end (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 back-end 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 Red Hat 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 or FastCGI sub-component within a pure java application server or be installed as a Apache/IIS module. 

   <li> As a script extension within a pure java application (requires Java >= 1.6).

</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> Configured and compiled to run without java. The GNU gcc 4
compiler library gcj can used to interpret java libraries. Thus it is
possible to use popular java libraries such as Apache's lucene or
Lowagi's itext directly from PHP, without the need to install a java
VM.

   <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 Unix, Windows or Linux system, <a href="http://www.sourceforge.net/projects/php-java-bridge">download</a> either the binary or the source and install it.
<H2>Installation on Linux</H2>
Open a command shell and type the following commands:
<H3>Public key</H3>
All binary files are digitally signed. Before you install the RPM binaries you should install the <a href="RPM-GPG-KEY">public key</a>, so that the integrity can be checked. If you haven't installed the key, type: 
<blockquote>
<code>rpm --import RPM-GPG-KEY</code>
</blockquote>
<H3>RPM binaries</H3>
Either install the bridge and standalone back-end
<p>
<blockquote>
<code>
rpm -i jdk-1_5_0-linux-i586.rpm<br>
rpm -i php-java-bridge-x.y.z-1-i386.rpm <br>
rpm -i php-java-bridge-standalone-x.y.z-1-i386.rpm<br>
</code> 
</blockquote>
</p>
or the tomcat back-end
<p>
<blockquote>
<code>
rpm -i tomcat5-5.0.30-5jpp_6fc.i386.rpm<br>
rpm -i php-java-bridge-tomcat-x.y.z-1.i386.rpm
</code>
</blockquote>
</p>
or the development files for JDK 1.6
<p>
<blockquote>
<code>
rpm -i jdk-6-linux-i586.rpm<br>
rpm -i rpm -i php-java-bridge-devel-x.y.z-1.i386.rpm<br>
</code>
</blockquote>
</p>
If you run a 64bit system <em>and</em> a 64bit JVM, you need to build a  64bit RPM using the command:
<p>
<blockquote>
<code>
rpmbuild --rebuild php-java-bridge-x.y.z-1.src.rpm<br>
</code>
</blockquote>
</p>
If you have installed the development RPM, you can run PHP scripts interactively, either from your Eclipse IDE (when available) or with the <a href="http://java.sun.com/javase/6/docs/tooldocs/share/jrunscript.html"><code>jrunscript</code></a> command:
<p>
<blockquote>
<code>
/usr/java/default/bin/jrunscript -l php-interactive
</code>
</blockquote>
</p>
<H2>Installation from source</H2>
 For other operating systems, e.g. Solaris, Windows, BSD or Mac-OSX, please follow 
the instructions below (on Security Enhanced Linux please use the RPM or please read the README before installation).</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>GNU autoconf </em> 2.57 or higher, <em>GNU libtool</em> 1.4.3 or higher, <em>GNU automake</em> 1.6.3 or higher, GNU make and php 4.3.4 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># compile with jdk1.4, use jre1.6 at run-time<br>
phpize &amp;&amp; ./configure
	--with-java=/usr/java/jdk1.4,/usr/java/jre1.6 &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>: 
<br><br>
<code>
Do you want to install the Servlet/J2EE back-end (recommended)?<br>
install j2ee back-end (yes/no): no<br>
<br>
Do you want to start the standalone back-end from a service script?<br>
install service script (yes/no): no<br>
</code>
<br>
The created PHP ini file (usually <code>java.ini</code> located in <code>/etc/php.d/</code> or <code>php.ini</code> located in <code>c:\winnt\</code>) should contain:
	<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 back-end 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:
<br><br>
<code>
Do you want to install the Servlet/J2EE back-end (recommended)?<br>
install j2ee back-end (yes/no): no<br>
<br>
Do you want to start the standalone back-end from a service script?<br>
install service script (yes/no): yes<br>
run the back-end with limited rights (yes/no): yes<br>
run the back-end as user (default: apache): <br>
run the back-end as group (default: apache): <br>
location of the java executable (/usr/bin/java): /opt/jdk1.5/jre/bin/java<br>
start now? (yes/no): yes<br>
</code>
<br>
The <code>java.socketname</code> has been set to the name of the socket, it will be created, if it doesn't exist.  The java section of the created PHP ini file (usually <code>java-standalone.ini</code> located in <code>/etc/php.d</code> or <code>php.ini</code> located in <code>c:\winnt\</code>) file should contain a <code>java.socketname</code> option. The following is an example from Red Hat 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 back-end as a 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 fail over</strong> or <strong>session sharing between PHP, JSP and Servlets</strong> it is recommended deploy the back-end into a servlet engine or an application server; <a href="http://www.onjava.com/pub/a/onjava/2004/03/31/clustering.html">a tomcat 5 cluster</a> for example:
<br><br>
<code>
Do you want to install the Servlet/J2EE back-end (recommended)?<br>
install j2ee back-end (yes/no): yes<br>
<br>
Enter the location of the autodeploy folder.<br>
autodeploy (/usr/share/tomcat5/webapps): /opt/SUNWappserver/domains/domain1/autodeploy<br>
</code>
<br>
The created PHP ini file (usually <code>php-servlet.ini</code> located in <code>/etc/php.d</code> or <code>php.ini</code> located in <code>c:\winnt\</code>) 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>
If you don't have Apache or IIS, install PHP as a CGI or FastCGI binary so that your application server <a href="server/documentation/API/php/java/bridge/Util.html#DEFAULT_CGI_LOCATIONS">can find it</a> or <a href="server/WEB-INF/web.xml"> enable the <code>php_exec</code> setting</a> and start the application server.
</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 back-end. Must be an integer, if a secure "Unix domain" channel is not available (Windows, Mac OSX).</TD
><TD
>java.socketname="9267"
</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 back-end.</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 back-end is not available.</TD
><TD
>java.hosts="127.0.0.1:9268;127.0.0.1:9269"
</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> back-ends. The option <code>User</code> preserves the context, <code>On</code> is for backward compatibility and rewrites the context to: <code>/JavaBridge/JavaBridge.phpjavabridge</code>.</TD
><TD
><code>;; Make sure that this option is only set <br>;; if your back-end 
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="/usr/local/lib"
</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
><TR
><TD
><A name="persistent_connections">java.persistent_connections</A></TD
><TD
>On</TD
><TD
>Use persistent connections to the back-end. If this flag is set to <code>On</code>, the Apache/Tomcat combination delivers java based content as fast as
Tomcat standalone.</TD
><TD
>
java.persistent_connections=Off
</TD
></TR
><TR
><TD
><A name="security_policy">java.security_policy</A></TD
><TD
>Off</TD
><TD
>Use the policy file <a href="server/javabridge.policy"><code>javabridge.policy</code></a> located in the PHP extension directory or the specified policy file.</TD
><TD
>
java.security_policy="c:/windows/javabridge.policy"
</TD
></TR
></TBODY
></TABLE
>
</center>
<br><br>
<H2>Further information</H2>
<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>, <a href="INSTALL.WEBSPHERE">INSTALL.WEBSPHERE</a>, <a href="INSTALL.ORACLE">INSTALL.ORACLE</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 back-end needs the specified versions of <em>GNU autoconf</em>, <em>GNU libtool</em> and <em>GNU automake</em> in the path. Don't try to re-use specialized versions which came with your operating system (e.g. symlink libtool-1.5 to libtool), this will not work; if you don't have autoconf 2.59, automake 1.9 and libtool 1.5.20, you must compile and install them, as described in the INSTALL document. 
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&id=679233">open
a problem report instead</a> (you don't need an account to submit a
problem report).
</p><p>
If Java or Mono is not installed on the build machine, 
the back-end compilation can be switched off with the <code>--disable-backend</code> configure option. A compiled, platform-independent back-end ("JavaBridge.war") can be found in the download folder.
</p> <p>On RPM based Security Enhanced Linux
installations (RHEL, Fedora) please install one of the binary RPMs or
compile a binary RPM from the source RPM using the command:
<code>rpmbuild --rebuild php-java-bridge*src.rpm</code> and install it.</p> <p>On
recent Debian X86 installations, Ubuntu for example, it is also
possible to install the RPM binaries: Open the <a href="#binary-versions">appropriate binary RPM</a>
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>
<p>
<A NAME="binary-versions"></A>
<center>
<B
>Table 3. Binary Versions</B
></P
>
<TABLE
BORDER="1"
><COL><COL><COL><COL><THEAD
><TR
><TH
>Name</TH
><TH
>ABI</TH
></TR
></THEAD><TBODY
><TR
><TD
>php-java-bridge-x.y.z-1.RHEL.i386.rpm</TD
><TD
>PHP 4 (&gt;= 4.3.2)</TD
></TR
>
<TR
><TD
>php-java-bridge-x.y.z-1.FC4.i386.rpm</TD
><TD
>PHP 5.0.x</TD
></TR
>
<TR
><TD
>php-java-bridge-x.y.z-1.FC5.i386.rpm</TD
><TD
>PHP 5.1 or PHP 6.x</TD
></TR
>
</TBODY>
</TABLE
>
</center>
 

<li> <H4>Can I use java libraries without
installing java?</H4> <p>Yes. Simply ommit the
<code>--with-java=</code> configure option. The <a href="README.GNU_JAVA">bridge will use the
<code>libgcj</code> library</a>, which is part of the GNU gcc compiler. 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 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.</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 sugar 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#a25">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 <a href="server/javabridge.policy">example file</a> has been installed in the php extension directory and can be enabled with:
<code>
java.security_policy=On
</code>
 </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 back-end 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 back-end 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 BSH 2.0 code<br>
<p>
<code>
buf=new java.lang.StringBuffer();<br>
<br>
int i=0;<br>
while(i<400000) {<br>
&nbsp;&nbsp;i=i+1;<br>
&nbsp;&nbsp;buf.append(new String(String.valueOf(i)));<br>
}<br>
<br>
print (buf.length()); print("\n");<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
>time jrunscript -l bsh t11.bsh</TD
><TD
>BSH 2.0</TD
><TD
>none (native code)</TD
><TD
>0m21.342s,<br>
0m20.779s,<br>
0m0.291s
</TD
></TR
>
</TBODY>

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

</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 a standalone back-end, 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 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?</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 -Dphp.java.bridge.base=... 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 wrapper <code>RunJavaBridge</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> <a name="global-servlet"><H4>I want to use PHP for all tomcat applications. Apache and IIS are not available, but performance is important. How do I install it?</H4></a>
<p> Check if your PHP cgi binary supports the <code>-b</code> flag. If not, compile PHP with the <code>--enable-fastcgi</code> option or <a href="#http-front-end">use Apache or IIS as a front-end</a> instead.</p>
<p>
Download and install the J2EE binary: copy <code>JavaBridge.war</code> into the tomcat <code>webapps</code> folder.
</p>
<p>
Copy the <code>JavaBridge.jar</code> and the <code>php-servlet.jar</code> from the JavaBridge.war into the tomcat <code>shared/lib</code> folder. Uncomment the <code>shared_fast_cgi_pool</code> parameter in the <code>JavaBridge/WEB-INF/web.xml</code> and add the lines marked with a <code>+</code> to the tomcat <code>conf/web.xml</code>:
<blockquote>
<code>
<br>
   &lt;!-- ================== Built In Servlet Definitions ==================== --&gt;<br>
<br>
+    &lt;!-- PHP Servlet --&gt;<br>
+    &lt;servlet&gt;<br>
+        &lt;servlet-name&gt;GlobalPhpJavaServlet&lt;/servlet-name&gt;<br>
+        &lt;servlet-class&gt;php.java.servlet.PhpJavaServlet&lt;/servlet-class&gt;<br>
+    &lt;/servlet&gt;<br>
+    &lt;!-- PHP CGI Servlet --&gt;<br>
+    &lt;servlet&gt;<br>
+        &lt;servlet-name&gt;GlobalPhpCGIServlet&lt;/servlet-name&gt;<br>
+        &lt;servlet-class&gt;php.java.servlet.PhpCGIServlet&lt;/servlet-class&gt;<br>
+        &lt;init-param&gt;<br>
+        &lt;!-- Remember to set the shared_fast_cgi_pool option --&gt;<br>
+        &lt;!-- in JavaBridge/WEB-INF/web.xml to On, too. --&gt;<br>
+        &lt;param-name&gt;shared_fast_cgi_pool&lt;/param-name&gt;<br>
+        &lt;param-value&gt;On&lt;/param-value&gt;<br>
+        &lt;/init-param&gt;<br>
+    &lt;/servlet&gt;<br>
<br>
   &lt;!-- The default servlet for all web applications, that serves static     --&gt;<br>
   &lt;!-- resources.  It processes all requests that are not mapped to other   --&gt;<br>
[...]<br>
   &lt;!-- ================ Built In Servlet Mappings ========================= --&gt;<br>
<br>
+    &lt;!-- PHP Servlet Mapping --&gt;<br>
+    &lt;servlet-mapping&gt;<br>
+        &lt;servlet-name&gt;GlobalPhpJavaServlet&lt;/servlet-name&gt;<br>
+        &lt;url-pattern&gt;*.phpjavabridge&lt;/url-pattern&gt;<br>
+    &lt;/servlet-mapping&gt;<br>
+    &lt;!-- CGI Servlet Mapping --&gt;<br>
+    &lt;servlet-mapping&gt;<br>
+        &lt;servlet-name&gt;GlobalPhpCGIServlet&lt;/servlet-name&gt;<br>
+        &lt;url-pattern&gt;*.php&lt;/url-pattern&gt;<br>
+    &lt;/servlet-mapping&gt;<br>
<br>
   &lt;!-- The servlet mappings for the built in servlets defined above.  Note  --&gt;<br>
   &lt;!-- that, by default, the CGI and SSI servlets are *not* mapped.  You    --&gt;<br>
<br>
 &lt;/web-app&gt;<br>
</code>
</blockquote>
</p>
To test the above settings create a directory <code>testapp</code> and copy the <code>test.php</code> file from the <code>JavaBridge.war</code> into this folder. Type <code>cd testapp; jar cf ../testapp.war *</code> and copy the testapp.war into the tomcat <code>webapps</code> folder.
Restart tomcat, browse to 
<code>http://yourHost.com:8080/testapp/test.php</code>.
</p>
<p>
Check if the PHP Fast-CGI server is running. The process list should display 20 (default) PHP instances waiting in the PHP Fast-CGI pool. If not, check if your PHP binary has been compiled with Fast-CGI enabled. Copy a Fast-CGI enabled binary into the <code>webapps/JavaBridge/WEB-INF/cgi/</code> folder, if necessary.
</p>

<li> <a name="php-web-app"><H4>How do I create a standalone PHP web application for distribution and how can users deploy it into tomcat?</H4></a>
<p>
Create a directory <code>myApplication</code>, create the directories <code>myApplication/WEB-INF/lib/</code> and <code>myApplication/WEB-INF/cgi/</code>.
Download the J2EE binary and copy the <code>JavaBridge.jar</code> and the <code>php-servlet.jar</code> from the JavaBridge.war to the <code>myApplication/WEB-INF/lib/</code> folder. Copy the contents of the <code>cgi</code> folder to <code>myApplication/WEB-INF/cgi/</code>. Create the file <code>myApplication/WEB-INF/web.xml</code> with the following content:
<blockquote>
<code>
<br>
&lt;web-app&gt;<br>
    &lt;!-- PHP Servlet --&gt;<br>
    &lt;servlet&gt;<br>
        &lt;servlet-name&gt;PhpJavaServlet&lt;/servlet-name&gt;<br>
        &lt;servlet-class&gt;php.java.servlet.PhpJavaServlet&lt;/servlet-class&gt;<br>
    &lt;/servlet&gt;<br>
    &lt;!-- PHP CGI processing servlet, used when Apache/IIS are not available --&gt;<br>
    &lt;servlet&gt;<br>
        &lt;servlet-name&gt;PhpCGIServlet&lt;/servlet-name&gt;<br>
        &lt;servlet-class&gt;php.java.servlet.PhpCGIServlet&lt;/servlet-class&gt;<br>
    &lt;/servlet&gt;<br>
<br>
    &lt;!-- PHP Servlet Mapping --&gt;<br>
    &lt;servlet-mapping&gt;<br>
        &lt;servlet-name&gt;PhpJavaServlet&lt;/servlet-name&gt;<br>
        &lt;url-pattern&gt;*.phpjavabridge&lt;/url-pattern&gt;<br>
    &lt;/servlet-mapping&gt;<br>
    &lt;!--PHP CGI Servlet Mapping --&gt;<br>
    &lt;servlet-mapping&gt;<br>
        &lt;servlet-name&gt;PhpCGIServlet&lt;/servlet-name&gt;<br>
        &lt;url-pattern&gt;*.php&lt;/url-pattern&gt;<br>
    &lt;/servlet-mapping&gt;<br>
<br>
    &lt;!-- Welcome files --&gt;<br>
    &lt;welcome-file-list&gt;<br>
        &lt;welcome-file&gt;index.php&lt;/welcome-file&gt;<br>
    &lt;/welcome-file-list&gt;<br>
 &lt;/web-app&gt;<br>
</code>
</blockquote>
</p>
<p>
Copy the files <code>sessionSharing.jsp</code> and <code>sessionSharing.php</code> from the <code>JavaBridge.war</code> to <code>myApplication</code> and create <code>myApplication.war</code>, for example with the commands: <code>cd myApplication; jar cf ../myApplication.war *</code>. </p>
<p>The web archive can now be distributed, copy it to the tomcat <code>webapps</code> directory and re-start tomcat. Visit <code>http://localhost/myApplication/sessionSharing.php</code> and <code>http://localhost/myApplication/sessionSharing.jsp</code>.
</p>
<li> <a name="http-front-end"><H4>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?</H4></a>
<p>
Download and install the J2EE binary: copy <code>JavaBridge.war</code> into the tomcat <code>webapps</code> folder.
Check if the tomcat <code>webapps</code> directory is shared with the Apache/IIS <code>htdocs</code> directory. If not, change the Apache/IIS setting, the following example is for Apache 2. Edit e.g. <code>/etc/httpd/conf/httpd.conf</code> as follows: 
<blockquote>
<code>
 # documents. By default, all requests are taken from this directory, but<br>
 # symbolic links and aliases may be used to point to other locations.<br>
 #<br>
-DocumentRoot "/var/www/html"<br>
+DocumentRoot "/var/lib/tomcat5/webapps"<br>
<br>
 #<br>
 # Each directory to which Apache has access can be configured with respect<br>
 #<br>
 # This should be changed to whatever you set DocumentRoot to.<br>
 #<br>
-&lt;Directory "/var/www/html"&gt;<br>
+&lt;Directory "/var/lib/tomcat5/webapps"&gt;<br>
</code>
</blockquote>
</p>
<p>
Edit the <code>php.ini</code> or add a file <code>php-tomcat.ini</code> to the directory which contains the PHP module descriptions (usually <code>/etc/php.d/</code>), so that it contains:
<blockquote>
<code>
[java]<br>
java.hosts = 127.0.0.1:8080<br>
java.servlet = On<br>
</code>
</blockquote>
</p>
To test the above settings create a directory <code>testapp</code> and copy the <code>sessionSharing.php</code> file from the <code>JavaBridge.war</code> into this folder. Type <code>cd testapp; jar cf ../testapp.war *</code> and copy the testapp.war into the tomcat <code>webapps</code> folder.
Restart Apache or IIS and tomcat, browse to 
<code>http://localhost/testapp</code>, click on sessionSharing.php and check the generated cookie value. The <code>path</code> value must be <code>/</code>.
</p>
<li> <a name="php-jsp-session-sharing"><H4>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?</H4></a>
<p>
Download the J2EE binary and copy the <code>JavaBridge.jar</code> and the <code>php-servlet.jar</code> from the JavaBridge.war into the tomcat <code>shared/lib</code> folder. Add the lines marked with a <code>+</code> to the tomcat <code>conf/web.xml</code>:
<blockquote>
<code>
<br>
   &lt;!-- ================== Built In Servlet Definitions ==================== --&gt;<br>
<br>
+    &lt;!-- PHP Servlet --&gt;<br>
+    &lt;servlet&gt;<br>
+        &lt;servlet-name&gt;GlobalPhpJavaServlet&lt;/servlet-name&gt;<br>
+        &lt;servlet-class&gt;php.java.servlet.PhpJavaServlet&lt;/servlet-class&gt;<br>
+    &lt;/servlet&gt;<br>
<br>
   &lt;!-- The default servlet for all web applications, that serves static     --&gt;<br>
   &lt;!-- resources.  It processes all requests that are not mapped to other   --&gt;<br>
[...]<br>
   &lt;!-- ================ Built In Servlet Mappings ========================= --&gt;<br>
<br>
+    &lt;!-- PHP Servlet Mapping --&gt;<br>
+    &lt;servlet-mapping&gt;<br>
+        &lt;servlet-name&gt;GlobalPhpJavaServlet&lt;/servlet-name&gt;<br>
+        &lt;url-pattern&gt;*.phpjavabridge&lt;/url-pattern&gt;<br>
+    &lt;/servlet-mapping&gt;<br>
<br>
   &lt;!-- The servlet mappings for the built in servlets defined above.  Note  --&gt;<br>
   &lt;!-- that, by default, the CGI and SSI servlets are *not* mapped.  You    --&gt;<br>
<br>
 &lt;/web-app&gt;<br>
</code>
</blockquote>
</p>
<p>
Check if the tomcat <code>webapps</code> directory is shared with the Apache/IIS <code>htdocs</code> directory. If not, change the Apache/IIS setting, the following example is for Apache 2. Edit e.g. <code>/etc/httpd/conf/httpd.conf</code> as follows: 
<blockquote>
<code>
 # documents. By default, all requests are taken from this directory, but<br>
 # symbolic links and aliases may be used to point to other locations.<br>
 #<br>
-DocumentRoot "/var/www/html"<br>
+DocumentRoot "/var/lib/tomcat5/webapps"<br>
<br>
 #<br>
 # Each directory to which Apache has access can be configured with respect<br>
 #<br>
 # This should be changed to whatever you set DocumentRoot to.<br>
 #<br>
-&lt;Directory "/var/www/html"&gt;<br>
+&lt;Directory "/var/lib/tomcat5/webapps"&gt;<br>
</code>
</blockquote>
</p>
<p>
Now that tomcat knows how to handle PHP <code>.phpjavabridge</code> requests and Apache or IIS can access the tomcat webapps, connect the two components: Edit the <code>php.ini</code> or add a file <code>php-tomcat.ini</code> to the directory which contains the PHP module descriptions (usually <code>/etc/php.d/</code>), so that it contains:
<blockquote>
<code>
[java]<br>
java.hosts = 127.0.0.1:8080<br>
java.servlet = User<br>
</code>
</blockquote>
The above <code>User</code> setting enables session sharing between PHP and JSP, it forwards from <code>http://host<em>/myApp/foo.php</em></code> to the tomcat back-end at <code>127.0.0.1:8080</code> using the request <code>PUT <em>/myApp/foo.php</em>javabridge</code>. This triggers the <code>GlobalPhpJavaServlet</code> configured in the tomcat <code>web.xml</code>.
</p>
<p>
Now you need to do the same for JSP. Unlike the PHP/Java Bridge, which only forwards embedded java statements, the tomcat <code>mod_jk</code> adapter must forward all JSP requests.
Download and install <code>mod jk</code>, for example
<code>jakarta-tomcat-connectors-1.2.14.1-src.tar.gz</code>, extract the file into a
folder and type the following commands:
<blockquote>
<code>
cd jakarta-tomcat-connectors-1.2.14.1-src/jk/native/<br>
./configure --with-apxs && make && su -c "make install"<br>
</code>
</blockquote>
Add the following lines to the end of the <code>httpd.conf</code>, the following example is for Apache 2:
<blockquote>
<code>
LoadModule jk_module modules/mod_jk.so<br>
JkAutoAlias /var/lib/tomcat5/webapps<br>
JkMount *.jsp ajp13<br>
</code>
</blockquote>
</p>
To test the above settings create a directory <code>testapp</code> and copy the <code>sessionSharing.php</code> and <code>sessionSharing.jsp</code> from the <code>JavaBridge.war</code> into this folder. Type <code>cd testapp; jar cf ../testapp.war *</code> and copy the testapp.war into the tomcat <code>webapps</code> folder.
Restart Apache or IIS and tomcat, browse to 
<code>http://localhost/testapp</code>, click on sessionSharing.php and check the generated cookie value. The <code>path</code> value must be <code>/testapp</code>. Click on sessionSharing.jsp.
</p>
<li> <H4>How does the bridge handle OutOfMemoryErrors?</H4> 
<p>
OutOfMemoryErrors may happen because a cached object cannot be released, either because <p>
<ol>
<li> the object is permanently referenced by a request-handling thread or
<li> the object has been entered into the session or application store or 
<li> the object 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 back-end with e.g.:<br><br>
<code>
java -agentlib:hprof=heap=sites -jar JavaBridge.jar<br>
</code>
</p>
<li> <H4>The EJB example works with the Sun J2EE server, but in JBoss I get a ClassCastException, what's wrong?</H4> 
<p>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 <code>documentClient.jar</code> as a library, so JBoss references the library classes instead of the bean classes. Just remove the <code>documentClient.jar</code> from the <code>JavaBridge.war</code>, re-deploy <code>JavaBridge.war</code> and run the test again.
</p><p>
In JBoss' default setup the code:
<blockquote>
<code>
  // access the home interface<br>
  $DocumentHome = new JavaClass("DocumentHome");<br>
  $PortableRemoteObject = new JavaClass("javax.rmi.PortableRemoteObject");<br>
  $home=$PortableRemoteObject-&gt;narrow($objref, $DocumentHome);<br>
</code>
</blockquote>
refences the <code>DocumentHome</code> from the library, which is assignment-incompatible to <code>DocumentHome</code> from the enterprise bean (<code>DocumentHome@WebAppClassLoader</code> !=  <code>DocumentHome@BeanClassLoader</code>), so you get a ClassCastException in <code>narrow</code>.
</p>
<p>
In contrast the Sun J2EE server correctly separates the beans/applications; the <code>$objref</code> is a unique proxy generated by a parent of the <code>WebAppClassLoader</code>, so that <code>narrow</code> can always cast the proxy to <code>DocumentHome@WebAppClassLoader</code>, even if a class with the same name is already available from the <code>WebAppClassLoader</code>.</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/RMI-IIOP/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.