PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<ircg_whoisjava_last_exception_clear>
view the version of this page
Last updated: Thu, 21 Aug 2003

XLVI. PHP / Java Integration

Introduction

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.

The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.

Warning

This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk.

Requirements

You need a Java VM installed on your machine to use this extension.

Installation

To include Java support in your PHP build you must add the option --with-java[=DIR] where DIR points to the base install directory of your JDK. This extension can only be built as a shared dl. More build instructions for this extension can be found in php4/ext/java/README.

Note to Win32 Users: In order to enable this module on a Windows environment with PHP <= 4.0.6, you must copy jvm.dll from the DLL folder of the PHP/Win32 binary package to the SYSTEM32 folder of your windows machine. (Ex:C:\WINNT\SYSTEM32 or C:\WINDOWS\SYSTEM32). For PHP > 4.0.6 you do not need any additional dll file.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 1. Java configuration options

NameDefaultChangeable
java.class.pathNULLPHP_INI_ALL
java.homeNULLPHP_INI_ALL
java.library.pathNULLPHP_INI_ALL
java.libraryJAVALIBPHP_INI_ALL
For further details and definition of the PHP_INI_* constants see ini_set().

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Examples

Example 1. Java Example

<?php
  // get instance of Java class java.lang.System in PHP
  $system = new Java('java.lang.System');

  // demonstrate property access
  print 'Java version='.$system->getProperty('java.version').' <br>';
  print 'Java vendor=' .$system->getProperty('java.vendor').' <br>';
  print 'OS='.$system->getProperty('os.name').' '.
              $system->getProperty('os.version').' on '.
              $system->getProperty('os.arch').' <br>';

  // java.util.Date example
  $formatter = new Java('java.text.SimpleDateFormat',
                        "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");

  print $formatter->format(new Java('java.util.Date'));
?>

Example 2. AWT Example

<?php
  // This example is only intented to be run as a CGI.

  $frame  = new Java('java.awt.Frame', 'PHP');
  $button = new Java('java.awt.Button', 'Hello Java World!');

  $frame->add('North', $button);
  $frame->validate();
  $frame->pack();
  $frame->visible = True;

  $thread = new Java('java.lang.Thread');
  $thread->sleep(10000);

  $frame->dispose();
?>
Notes:

  • new Java() will create an instance of a class if a suitable constructor is available. If no parameters are passed and the default constructor is useful as it provides access to classes like java.lang.System which expose most of their functionallity through static methods.

  • Accessing a member of an instance will first look for bean properties then public fields. In other words, print $date.time will first attempt to be resolved as $date.getTime(), then as $date.time.

  • Both static and instance members can be accessed on an object with the same syntax. Furthermore, if the java object is of type java.lang.Class, then static members of the class (fields and methods) can be accessed.

  • Exceptions raised result in PHP warnings, and NULL results. The warnings may be eliminated by prefixing the method call with an "@" sign. The following APIs may be used to retrieve and reset the last error:

  • Overload resolution is in general a hard problem given the differences in types between the two languages. The PHP Java extension employs a simple, but fairly effective, metric for determining which overload is the best match.

    Additionally, method names in PHP are not case sensitive, potentially increasing the number of overloads to select from.

    Once a method is selected, the parameters are cooerced if necessary, possibly with a loss of data (example: double precision floating point numbers will be converted to boolean).

  • In the tradition of PHP, arrays and hashtables may pretty much be used interchangably. Note that hashtables in PHP may only be indexed by integers or strings; and that arrays of primitive types in Java can not be sparse. Also note that these constructs are passed by value, so may be expensive in terms of memory and time.

Java Servlet SAPI

The Java Servlet SAPI builds upon the mechanism defined by the Java extension to enable the entire PHP processor to be run as a servlet. The primary advanatage of this from a PHP perspective is that web servers which support servlets typically take great care in pooling and reusing JVMs. Build instructions for the Servlet SAPI module can be found in php4/sapi/README. Notes:

  • While this code is intended to be able to run on any servlet engine, it has only been tested on Apache's Jakarta/tomcat to date. Bug reports, success stories and/or patches required to get this code to run on other engines would be appreciated.

  • PHP has a habit of changing the working directory. sapi/servlet will eventually change it back, but while PHP is running the servlet engine may not be able to load any classes from the CLASSPATH which are specified using a relative directory syntax, or find the work directory used for administration and JSP compilation tasks.

Table of Contents
java_last_exception_clear -- Clear last Java exception
java_last_exception_get -- Get last Java exception


add a note add a note User Contributed Notes
PHP / Java Integration
g dot mourgues at mialys dot com
15-Sep-2003 02:32
Mandrake 9.1 - Apache 2.0.47 - PHP 4.3.3 - Java J2sdk 1.4.2

 I followed the note of phpnet AT devnull DOT org DOT uk. Everything works except that ldconfig is needed every time I reboot the system (so I added it in httpd).
Thanks for all help.
phpnet AT devnull DOT org DOT uk
15-Jul-2003 04:46
Red Hat Linux release 7.2 (i386)
apache 1.3.27
php 4.2.3
j2sdk1.4.2

I followed all the notes in this thread and managed to get it to work for the system described above.
Apache kept hanging until I added pthreads to the apache build.
So all in one place the things u need to get it working for the system noted above.
It follows on from all the hard work/effort from the previous posts (thanks guys!!!),
i take no credit - this just an extra bit of help..

Apache
--------
Apache needs pthreads, you can do it before the configure command, ie:
      LDFLAGS=-lpthread ./configure --prefix=/www/web1 \ etc etc

After it is installed, edit apachectl and add at the top somewhere:
     export    LD_LIBRARY_PATH=$JAVA_HOME/jre/lib/i386:$JAVA_HOME/jre/lib/i386/server

I tried to add those paths to /etc/ld.so.conf (and running ldconfig -v)
but a test php page with: 
     echo "<PRE>";
     system("ldd /usr/java/j2sdk1.4.2/jre/lib/i386/*")
showed many "not founds"
therefore I stuck with the LD_LIBRARY_PATH
ran it again and all was ok - all the libraries resolved ok.
Setting the LD_LIBRARY_PATH correctly should dissolve all errors such as:
 Cannot instantiate non-existent class:
 cannot open shared object file:
 Unable to load Java Library

PHP
----
Compile with
    --with-java=PATH_TO_JAVA_HOME
mine is:
    --with-java=/usr/java/j2sdk1.4.2

php.ini settings - mod for your paths/versions
-----------------
[java]
java.class.path=/www/web1/conf/lib/php/php_java.jar
java.home = /usr/java/j2sdk1.4.2
java.library = /usr/java/j2sdk1.4.2/jre/lib/i386/libjava.so
java.library.path = /www/web1/conf/lib/php/extensions/no-debug-non-zts-20020429
extension_dir = /www/web1/conf/lib/php/extensions/no-debug-non-zts-20020429
extension=libphp_java.so

test
-----
make a test php page
just write:
    <?phpinfo() ?>
then save and browse to it.
check the java section to see if your php.ini settings are set

hack
-----
Finally, in the java.library.path dir where java.so lives
run the command 
    ln -s java.so libphp_java.so

edit a test file with the java code in at the top of this thread and all should b ok

any errors in the error_log - check that the LD_LIBRARY_PATH is really set

sorry if i have missed anything out
mail me a slap :O)
but its been an awful day today!
G00dLucK,
ells..
chris at mad-teaparty dot com
03-Jul-2003 11:32
This snippet shows how to write ZIP-Files using PHP's Java-API:

---------------------------
// specify the name of the zip file to be created
$zipfile = "/usr/local/apache/htdocs/skripte/test.zip";
// files that should be zipped
$filenames = array("test.php", "index.html");
// create a zip output stream
$out = new Java('java.util.zip.ZipOutputStream', new Java('java.io.FileOutputStream', $zipfile));
// walk through the array an add each file to the archive
foreach ($filenames as $entry) {
   $content = implode("", file($entry));  // read the file
   $zipentry = new Java('java.util.zip.ZipEntry', $entry);  //define a new zip entry
     $out->putNextEntry($zipentry);  //write this entry to the archive
   $out->write($content, 0, strlen($content));  //add the content
   $out->closeEntry();  // close the current entry
}
$out->setComment("test...");   // set a comment for the zip file
$out->close();  //close the output stream
----------------------------

This is just "proof of concept". It doesn't set all values for zip entries, like CRC32-checksum, compressed size etc.

Several hints:
- in order to read or write JAR-archives, the snippet needs only few modification: replace the ZIPOutputStream with an instance of "JarOutputStream" or "JarInputStream", defined in "java.util.jar"
- use double backslashes for path names on Windows, eg. "C:\\apache\\htdocs\\index.html"
- if you specify an absolute path name for a single zip entry, a directory will be created in the zip archive. Thus, you can "zip" whole directories by walking through them
- If you want to set the time when the zip entry was added, note that the Java-method "setTime" requires a long value (millisec). I did this:

$zipentry->setTime(time()*1000);

- If you want to add the CRC-checksum to each zip entry, do not (!) use PHP's crc32-function! Incompatible types will cause loss of precision and wrong checksums. Use the Java-class "CRC32" instead:

$crc32 = new Java('java.util.zip.CRC32');
$crc32->update($content);
$zipentry->setCrc($crc32->getValue());
$crc32->reset();
totschnig dot michael at uqam dot ca
01-Jul-2003 09:19
I'd like to share three observations about PHP's JAVA extension that might help others save some time:
1) On Redhat 7.3, with Apache 1.3.27 and PHP 4.3.2, I did not get to work PHP with Suns JDK 1.4.0_01 (Apache crashes), but JDK 1.4.2 works.
2) Calling a JAVA application with an exec call to a shell script seems considerably faster than accessing the same functionality with the JAVA extension. For example calling Fop with the JAVA extension can take 30 seconds on the same file, where the shell script from the Fop distribution (called from PHP with exec) takes 20 seconds.
3) When I recompile a Java class, it seems that the running httpd process, keeps the class file somewhere in cache, because I had to restart apache, before my PHP script, actually called the freshly compiled class.
chris at mad-teaparty dot com
15-Jun-2003 06:34
This snippet shows how to use Java's image-editing classes and methods in PHP. It creates a gradient-painted, shadowed text as a JPEG file.
Note:
- Unfortunately, it only works as a CGI. Tests failed with PHP compiled as an Apache Module on both Linux and Windows.
- If you don't specify an absolute path for your image, it will be created in your PHP directory.
- Running this script takes quite some time. (CGI, creating the JVM etc.)

<?php
// general settings
$imgName "php_java_image.jpg";
$message "mad-teaparty.com";
$fontName "Monospace";
$fontSize 80;
$startrgb = array(00255);  // color for gradient paint at the first point
$endrgb = array(000);       // color for gradient paint at the second point
$shadowrgb = array(204204204);  // color for the shadow
$bgrgb = array(255255255);    //color for the background

// create instances of 'java.awt.Color'
$endcol = new Java('java.awt.Color'$endrgb[0], $endrgb[1], $endrgb[2]);
$shadowcol = new Java('java.awt.Color'$shadowrgb[0], $shadowrgb[1], $shadowrgb[2]);
$startcol = new Java('java.awt.Color'$startrgb[0], $startrgb[1], $startrgb[2]);
$bgcol = new Java('java.awt.Color'$bgrgb[0], $bgrgb[1], $bgrgb[2]);
// create a Font object, style (2nd param) is bold (0 = plain, 2 = italic)
$font = new Java('java.awt.Font'$fontName1$fontSize);

/* Looks weird, but we need a dummy image object to get the
 * constants of 'java.awt.image.BufferedImage'
 * Thus, we can also get the FontMetrics and don't need to create a Frame
 * I haven't found a better solution yet
 */
$temp = new Java('java.awt.image.BufferedImage'111);
$tempg2d $temp->createGraphics();
$fontMetrics $tempg2d->getFontMetrics($font);

// calculate the dimensions that fit the message
$messageWidth $fontMetrics->stringWidth($message);
$imgWidth $messageWidth+2*$fontSize;
$imgHeight $fontSize*2;

// instantiate a BufferedImage with 8-bit color components
$img = new Java('java.awt.image.BufferedImage'$imgWidth$imgHeight$temp->TYPE_INT_RGB);
$g2d $img->createGraphics();   // get the Graphics2D object
$g2d->setPaint($bgcol);                // paint the background
$g2d->fillRect(00$imgWidth$imgHeight);
$g2d->setFont($font);                   // set the Font for our message
$g2d->translate(35$imgHeight*0.7);  // move the text so that it will be centered
$g2d->setPaint($shadowcol);      // set the color for the shadowed text
$affineTransform $g2d->getTransform();     // get an AffineTransform object
$g2d->shear(-1.00);              // shear the message by 45 deg to the right
$g2d->scale(11.5);                // resize, the shadowed text should be 1.5 times higher
$g2d->drawString($message00);        // draw the shadowed text
$g2d->setTransform($affineTransform);    // apply the transformation

// the spicy ingredient: a gradient-painted message in the foreground
$gpaint = new Java('java.awt.GradientPaint'00$startcol$imgWidth$imgHeight$endcol);
$g2d->setPaint($gpaint);
$g2d->drawString($message00);

// create a DataOutputStream for the JPEGEncoder
$out = new Java('java.io.DataOutputStream', new Java('java.io.FileOutputStream'$imgName));
// fortunately, we can instantiate the codec directly
$codec = new Java('com.sun.image.codec.jpeg.JPEGCodec');
// create the encoder with the given OutputStream
$encoder $codec->createJPEGEncoder($out);
$encodeParam $encoder->getDefaultJPEGEncodeParam($img);
// enable best quality, otherwise our JPEG gets blurred
$encodeParam->setQuality(1.0false);
$encoder->setJPEGEncodeParam($encodeParam);
$encoder->encode($img);   // output!!!
?>

This is just a short and popular example to proof the concept, but the result is already awesome!
By using the classes from the package 'java.awt.image' (Kernel, ConvolveOp, RescaleOp, etc.), you can perform even more advanced and professional image-editing operations.
Or use Acme's GIF-encoder instead of Sun's JPEG-encoder.
06-Jun-2003 03:03
I had a hard time (like most people here... ;) ) to find the right settings in php.ini. None of the solutions presented above worked for me. I installed PHP 4.3.2 as a DSO for Apache 1.3.27 under RedHat 9. I use the JDK from Sun (Version 1.4) and installed it under /usr/local/j2sdk1.4.0_01

One of the earlier postings (the one by fernando) gave me the crucial hint. While "java.library" has to point at "/usr/local/j2sdk1.4.0_01/jre/lib/i386/libjava.so" (as usual), the "java.library.path" must point at the directory where you've put your php-extensions! (in my case: "/usr/local/lib/php/extensions/no-debug-non-zts-20020429"). Summing up, my php.ini looks like this:

java.class.path = /usr/local/lib/php/php_java.jar
java.home = /usr/local/j2sdk1.4.0_01
java.library = /usr/local/j2sdk1.4.0_01/jre/lib/i386/libjava.so
java.library.path = /usr/local/lib/php/extensions/no-debug-non-zts-20020429

Don't forget to set LD_LIBRARY_PATH correctly. I added, like already metioned above, the following line to my startup script (/usr/local/apache/bin/apachectl):

export LD_LIBRARY_PATH=:/usr/local/j2sdk1.4.0_01/jre/lib/i386:
/usr/local/j2sdk1.4.0_01/jre/lib/i386/server

--------------

Note the following hints for troubleshooting:
- if you haven't set your LD_LIBRARY_PATH, you'll be reported that the file "libverify.so" can't be found. (This file is in "/usr/local/j2sdk1.4.0_01/jre/lib/i386")
- if your "java.library.path" in php.ini doesn't point at your php extensions directory (but eg. at your jre directory), the JRE will complain about the following: "UnsatisfiedLinkError". That means, that your corresponding php extension ("java.so" or "libphp_java.so") can't be detected! Have another look at the note posted by gturner.

Done so, it works fine. I hope this might be useful for someone reading this never-ending story ;)
golob a with tail gimb little spot org
03-Jun-2003 08:57
This module allows PHP to interact with some interesting pieces of software - for one, it allows PHP to convert XML FO files into PDF/PS/... with the use of Apache FOP processor.

Here's an example:
<?
$basedir 
= new Java("java.io.File"".");
$outdir = new Java("java.io.File""out");
$outdir->mkdirs();

$fofile = new Java("java.io.File"$basedir"xml/fo/helloworld.fo");
$pdffile = new Java("java.io.File"$outdir"ResultFO2PDF.pdf");

echo 
"Input: ".$fofile->toString()."\n";
echo 
"Output: ".$pdffile->toString()."\n";

$driver = new Java("org.apache.fop.apps.Driver");
$logger = new Java("org.apache.avalon.framework.logger.ConsoleLogger");
$driver->setLogger($logger);
$driver->setRenderer($driver->RENDER_PDF);
$out = new Java("java.io.FileOutputStream"$pdffile);
$driver->setOutputStream($out);
$in = new Java("java.io.FileInputStream"$fofile);
$driver->setInputSource(new Java("org.xml.sax.InputSource"$in));
$driver->run();
$in->close();
$out->close();
?>
francois dot turi at globecast dot com
02-May-2003 08:57
as stated in Bug #19937 dynamic extension loading fails

the construction of extension on Aix is buggy.
After a week research I found the following fix:

The following patch should fix problem of loading extension under AIX
4.3.3 like the java extension.

Under AIX, shared object are different from shared library.
The default library construction (as in the construction of
the JAVA extension) doesnt work correctly as it relies on dynamic
linking from a library when only a shared object is given.
An exception appear as illegal instruction.

The following configuration are missing:

First of all:
=============
 one should construct correctly the export definition of libphp4.so.
In configure the following line should be changed:

********************************
diff configure configure.orig (sorry no -b available under AIX)
78084,78086c78084
< # FTU export_symbols_cmds='$NM $libobjs $convenience |
$global_symbol_pipe | sed '\''s/.* //'\'' | sort | uniq >
$export_symbols'
< export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe |
sed '\''s/.* //'\'' | sort | uniq|awk -vlib=$SOHOME/$soname
 '\''BEGIN{printf "#!%s\n",lib}{print \$0}'\'' > $export_symbols'
< echo "FTU export_symbols_cmds=$export_symbols_cmds"
---
> export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe |
sed '\''s/.* //'\'' | sort | uniq > $export_symbols'
***************************

I added awk -vlib=$SOHOME/$soname
 '\''BEGIN{printf "#!%s\n",lib}{print \$0}'\''
To the pipe so the first line will be read as:
#!/your/path/to/your/libphp4.so

And the rest is identical.
Before compiling your library you should setup the SOHOME variable as
the path where your shared object (libphp4.so.0) will be running:

************
 export SOHOME=/s00/opendata/build/SSOD/php.430/current
************

Second important point:
========================
Refer the export file of php shared object in the construction of the
java extension:
When compiling the JAVA extension you have to setup the following
environement VARIABLE

*****************
export JAVA_SHARED_LIBADD="-Wl,-bI:.libs/libphp4.exp"
*****************

That line state that in the linking process (ld), the java extension
will use the libphp4.exp file to find undefined function or global
variable. By defaut such function will be resolve as running time.
On AIX such binding doesnt work because the libphp4.so is not a shared
library (doesnt appear in the genmkd listing) but a share object.
You have to specify the full path to your share object while linking it
to make him resolve correctly the reference to the Zend API.

Nota: the default exemple given to make an extension doesnt have that
problem because it doesnt call any Zend API function stored in the
libphp4.so.

External reference:
The followings redbooks explain the subtle difference between share
objects and shared library under AIX:
Understanding C and C++ development on AIX
chapter 3 Compiling and Linking

original
http://www.redbooks.ibm.com/pubs/pdfs/redbooks/sg245674.pdf

latest draft (for 5.L)
http://www.redbooks.ibm.com/redpieces/pdfs/sg245674.pdf

Last point:
===========
The extension java should be rename after construction to

cp -p  libjava.so.0  libphp_java.so

to work correctly.

About libtool:
==============

The first line in configure change the libtool which is in charge of
creating the dynamic library. I cannot figure out if the bug is a php
bug or a libtool bug.
kemccarthy_00 at yahoo dot com
17-Apr-2003 01:10
Installing J2sdk and php --with-java on a Linux RedHat 8 machine was easy but figuring out how to configure the php.ini was the hard part; each place we looked (docs,m boards,here) had a different configuration.
Distilling everything we've seen and using trial and error we found the following to work. Since we have several Apache 1.3.27 servers running with PHP 4.3.1 on the machine as a DSO on each, we added:
export LD_LIBRARY_PATH=
/usr/java/j2sdkversion/jre/lib/i386:
/usr/java/j2sdkversion/jre/lib/i386/server
in the apachectl script each specific to the servers we wanted to integrate.
Our /etc/init.d/apache script starts and stops all the servers and we want to be able to start/stop one or another separately as well.

In the php.ini file we added
[Java]
java.class.path=/usr/local/lib/php/php_java.jar
java.home=/usr/java
extension_dir=/usr/local/lib/php/extensions/no-debug-non-zts-20020429
extension=java.so

The library and library path is found from the LD_LIBRARY_PATH env var; indeed being explicit about them in the php.ini causes calls to new Java() to fail.
polrtex at yahoo dot com
13-Mar-2003 02:52
For setting up php and java on Windows it is important to remeber to add the quotation marks around the variables in php.ini, although you might not be using spaces in the directory names.
The default examples in php.ini do not include quotes. I am running php 4.2.2 and w2k.

java.class.path= "D:\Inetpub\scripts\php-4.2.2\extensions\php_java.jar;"
java.home= "d:\jdk1.4"
java.library= "d:\jdk1.4\jre\bin\client\jvm.dll"
java.library.path= "D:\Inetpub\scripts\php-4.2.2\extensions"

The same options without the quotes generate various errors : couldn't find the class I am trying to instantiate, or couldn't start the JVM.
malachi at eoti dot org
05-Mar-2003 07:12
JDK 1.4.1, Apache 2.0.43, PHP 4.3.1, WinXP:

I pretty quickly got the first example on this page working. I
was trying for quite some time to get the second one working
before I realized it would run from the Command-Line, but not
from the browser.  However, the first example does work fine
with JDK1.4...

extension_dir = C:\PHP\extensions\

extension=php_java.dll

[Java]
java.class.path = "c:\java\j2sdk1.4.1\lib\tools.jar;
     C:\php\extensions\php_java.jar;
     C:\twsrc\products\java\jars\TWCommon.jar;
     C:\twsrc\products\java\jars\jdom.jar"
java.home = "C:\java\j2sdk1.4.1_01\jre"
java.library = "C:\java\j2sdk1.4.1_01\jre\bin\server\jvm.dll"
java.library.path = "C:\PHP\extensions"
mikezivin at yahoo dot com
23-Feb-2003 09:42
You MUST put double quotes around your java.class.path or else you will get a "java.lang.ClassNotFoundException" in PHP.
becki at web dot de
31-Jan-2003 01:26
My solution for Suse 7.3, Sun Java 1.4.0 with PHP 4.3.0 as Command Line Interface (CLI) and dynamic Apache module (DSO):

1. Make sure, that Php is compiled --with-apxs and --with-java.
If you dont know that, phpinfo() or "php -i" helps.

2. Edit usr/local/lib/php.ini :
[Java]
java.class.path= /usr/local/lib/php/php_java.jar
java.home= /usr/java/j2sdk1.4.0/jre
extension_dir= /usr/local/lib/php/extensions/no-debug-non-zts-20020429
extension= java.so

3. Create Symlink:
cd  /usr/local/lib/php/extensions/no-debug-non-zts-20020429
ln -s java.so libphp_java.so

4. Edit /etc/init.d/apache :
Find the line:
LD_LIBRARY_PATH=some/path
and modify it to:
LD_LIBRARY_PATH=some/path:/usr/java/j2sdk1.4.0/jre/lib/i386:/usr/
java/j2sdk1.4.0/jre/lib/i386/server
And now restart apache with "rcapache restart"

Of course You have to adjust all pathnames to your needs!
Thanks to aruntheking at hotmail dot com and turman at dont-spam-me dot com. 'Hope this is helpful for sombody else.
raggha at hotmail dot com
13-Jan-2003 06:45
Just wanted to make available the solution I found posted on

   http://bugs.php.net/bug.php?id=18600

to solve the typical "Fatal error: Unable to Create Java Virtual Machine" trouble for Win32 users (thanks buddy):

[12 Dec 2002 9:19am] Alberto.Sarini@libero.it
Hi there,

I'm confirming C嶮ric's knowledge - java is running correctly from within PHP on Apache only when PHP is running as a CGI and not as a SAPI module. When running PHP as Apache SAPI Module after the restart Apache only fist access to php page using java is running OK, all next reloads of this page caused "Fatal error: Unable to create Java Virtual Machine
in ..." I think this could be still not solved bug.

Thanks
Alberto

BTW I'm running on:
OS:Win2000 Server SP2
Apache:1.3.27
PHP Version 4.3.0-dev (Build Date  Dec 12 2002 10:14:28)
Java version=1.4.1_01
Java vendor=Sun Microsystems Inc.
neil at lowden dot net
03-Jan-2003 05:41
** Success with W2K Server, PHP 4.3.0 as IIS5 SAPI module and J2SDK1.4.1_01 **

After a bunch of annoyingly spurious "access violation" and "Unable to create Java Virtual Machine" errors
I changed the php.ini setting for java.library from:

"C:\j2sdk1.4.1_01\jre\bin\client\jvm.dll"

to:

"C:\j2sdk1.4.1_01\jre\bin\server\jvm.dll"

All above examples now work perfectly incuding my own classes and those at
http://www.onlamp.com/pub/a/php/2001/06/14/php_jav.html (thanks to emilebosch above on 18-Oct-2001 07:19).
 
I'd really like to know the difference between 'client' and 'server' JVM versions if anyone can illuminate us.

Notes:

1. Manual install of PHP 4.3.0 to C:\php with the following relevant extracts from php.ini:

extension=php_java.dll
[Java]
java.class.path = "C:\php\extensions\php_java.jar;C:\java\packages\"
java.home = "C:\j2sdk1.4.1_01\bin"
java.library = "C:\j2sdk1.4.1_01\jre\bin\server\jvm.dll"
java.library.path = "C:\php\extensions"

2. Default installation of latest Java SDK from Sun

3. Win2K Server SP2 with all(?) patches

4. My own classes are placed in C:\java\packages\

Hope this helps some people.

Regards

-Neil
jason at buildernaut dot com
19-Dec-2002 10:28
ON Linux / Apache --with-apxs
Page cannot be displayed - Apache crapping out.
I spent a great deal of time getting this to work - but hey - I'm a newbie. 
One thing I did find was that I experienced an error I have not seen on this board or anywhere else in searches. 
If you try to run a test java .php page and you get a page cannot be displayed error, try adding the follwing to your apache startup script

export LD_LIBRARY_PATH=/usr/lib/j2sdk1.3/jre/lib/i386/server
:/usr/lib/j2sdk1.3/jre/lib/i386

And of course change to paths that mean something to you.
joey at creativejuices dot ws
12-Dec-2002 08:27
***  Win32 Users & Using Command-line Interface ***

First of all, this is AWESOME!!!!  I think PHP just took a huge leap forward with this capability!

Here is what you need:

In the Php.in file:

;Windows Extensions
extension=php_java.dll

[Java]
java.class.path = "C:\php\java\php_java.jar"
java.home = "C:\J2SDK_Forte\jdk1.4.0\jre"
java.library = "C:\J2SDK_Forte\jdk1.4.0\jre\bin\client\jvm.dll" 
java.library.path = "C:\php\extensions"

**** Don't forget the double-quotes in the values ! ****

Next, add the file type association for Windows 2000.

1) open Windows Explorer
2) Click the Tool Menu Item
3) Select "Folder Options"
4) Select "File Types" tab
5) Select "New"
6) Type in your file extension for php scripts, I suggest ".phx" without the double-quotes
7) Click "Ok"
8) Find that extension in the "File Types" list again.  You may have to back out and come back in to find it. 
9) Once you found that newly added php extension, select the "Advanced" button.  You can change the Icon here, but what you want to do is click the "New" button next to the "Actions" area.
10) For the "Action" value enter the value "open" without the quotes.
11) For the "Action used to perform this action:" value enter the value "C:\php\php-cli.exe -c C:\WINNT %1" without the quotes.

Lastly, add c:\php to you PATH Environment variable on your computer.

That should do it.  You can test it by creating a test.phx file and open a cmd (DOS) window and cd into that directory(eg. c:\junk) and just execute your test file like this: c:\junk test.phx

This should return you your results as expected.  If you don't know much about the php-cli.exe (cli = Command-Line Interface) go here http://www.php.net/manual/en/features.commandline.php.

I used the person's example at the top of this page and it worked. 

Now, if I can just figure out how to call my own custom classes that have their own packages.
mike [at] blamires (dot) co (dot) uk
07-Nov-2002 08:45
For win32 users: I spent some time wondering why the php session couln't find my classes/packages saved in my own custom classpath. even though the correct paths were specified in java.class.path. The reasons was as simple as double quotes. e.g.

java.class.path = c:\php\extensions\php_java.jar; c:\java\packages\  - incorrect, the packages & classes in c:\java\packages will not be found

java.class.path = "c:\php\extensions\php_java.jar;c:\java\packages\" - will find all your classes and packages in c:\java\packages

Thanks to PHP for another stunning feature.
Mike
aruntheking at hotmail dot com
09-Oct-2002 05:40
Something that i missed out in my above mentioned earlier note on the same
topic, Thanks to Pablo for reminding me the same

Important
-------------

After you have completed the above mentioned steps, open the httpd file in /etc/init.d and type the following lines

LD_LIBRARY_PATH=:/usr/local/j2sdk1.4.0_02/jre/lib/i386
:\/usr/local/j2sdk1.4.0_02/jre/lib/i386/server

else you will get an error stating libverify.so not found

Another process
---------------

Before compiling PHP complete the following steps:
edit your /etc/ld.so.conf file by adding the following two lines:

/usr/local/j2sdk1.4.0_02/jre/lib/i386
/usr/local/j2sdk1.4.0_02/jre/lib/i386/server

To make this change effect, type the following at the command prompt:

ldconfig

Now "cd" into /usr/local/j2sdk1.4.0_02/jre/lib/i386 directory and enter the following command:

ldd libjava.so

The response that you get back shouldn't contain any "not found" error messages. If you get any then you can add the path for

the "not found" file to /etc/ld.so.conf and redo the above mentioned steps till you don't get any error messages.

Now you can compile PHP in the process mentioned above and follow the rest of the steps.
pablo-at-godel.com.ar
01-Oct-2002 04:22
For those using Redhat 7.x and Sun JDK, you have to set in LD_LIBRARY_PATH the directory where libjava.so .

In my case it looks like:
LD_LIBRARY_PATH=:/usr/local/j2sdk1.4.0_02/jre/lib/i386:\
/usr/local/j2sdk1.4.0_02/jre/lib/i386/server

This solved my problem with libjava.so not finding libverify.so

Hopes this helps to save some time for others.. I spent a lot of time before figuring this one out...
aruntheking at hotmail dot com
19-Sep-2002 10:55
Installing PHP 4.2.3 on Red Hat Linux7.2
with Java Support-Arunoday
-------------------------------

PHP as CGI module
------------------

1. Download PHP from www.php.net
2. Copy the file in the folder you want to have it installed like
 /usr/local
3. Unpack the file using the following commands
gunzip php-4.2.3.tar.gz
tar xvf php-4.2.3.ta
This will create a directory php-4.2.3.
4. cd into the above mentioned directory and type
 ./configure --with-java=<java directory>
You can add more options with
configure.
For a full list of options type ./configure --help | more
   
5. If configure doesn't through any error then type make
6. To test make you can type make test
7. To complete the installation type make install
In all probability the actual binary that this will create
by the name php will be in
the /usr/local/bin directory.
This file should then be copied to your
cgi-bin directory[the webservers cgi-bin]

in my system i issued the following command
cd /usr/local/bin/php /var/www/cgi-bin/php.cgi

8. Modify the php.ini with the following lines
 
[java]
java.class.path=/usr/local/lib/php/php_java.jar
java.library.path=/usr/local/lib/php
/extensions/no-debug-non-zts-20020429
java.home=/usr/local/j2sdk1.4.0_02
java.library=java.so
extensions_dir=/usr/local/lib/php/extensions/no-debug-non-zts-20020429
extension=java.so

in all probability the php.ini file will be
in the php4.2.3/pear/tests directory
- u will need to copy it to the
/usr/local/lib directory and add the above lines

You will also need to cd into the directory specified in java.library.path
above and type the following
ln -s java.so libphp_java.so
This will make a symbolic link to java.so file through libphp_java.so.

A call to any of your PHP file will have to be like the following:
http://<yourhostname>/cgi-bin/php.cgi?<yourfilename>.php

PHP as Dynamic Shared Object
----------------------------
Retrieve PHP binary as mentioned above.
The configiration process will be different and will be as follows:
./configure --with-apxs=/usr/sbin/apxs
--with-java=/usr/local/j2sdk1.4.0_02 --with postgresql

postgresql is optional - u can leave it out if you donot want to use it.
apxs is required as it gives the directive to configure php as a dynamic shared object with Apache.
Advantage, it runs in the same memory space as Apache
and hence accessing of data is faster.
Apart from this there is no need to call the php interpreter (php.cgi) with every call to a PHP file.

Add the following lines in the php.ini file - it should be in /usr/local/lib

[Java]
java.class.path=/usr/local/lib/php/php_java.jar
:/usr/share/pgsql/jdbc7.1-1.2.jar:/var/www/html
java.home=/usr/local/j2sdk1.4.0_02
java.library=/usr/local/j2sdk1.4.0_02/jre/lib/i386/libjava.so
extension_dir=/usr/local/lib/php/extensions/no-debug-non-zts-20020429
extension=java.so

You will also need to cd into the directory specified in java.library.path
above and type the following
ln -s java.so libphp_java.so
This will make a symbolic link to java.so file through libphp_java.so.

Note: the jdbc7.1-1.2.jar file mentioned in java.class.path
is the JDBC part for Postgresql.
alexg at syspro dot co dot za
29-Aug-2002 01:50
According to an Article posted at:

http://www.zend.com/zend/week/week91.php#Heading7

there might be some problems with getting php and jdk-1.4 to work toghether.. I`ve tried (php-4.2.2 and jdk-4.1) with no success....
amtd at 163 dot net
11-Jun-2002 05:45
--php.ini-------------------------

[Java]
java.class.path = .\extensions\php_java.jar
java.home = c:\java
java.library = C:\java\jre\bin\server\jvm.dll
java.library.path = c:\apache\php\extensions

--system---------------------------

Windows 2000 P + Apache + SUN jdk 1.4.0-beta3

--app path---------------------------

java(C:\java)
Apache(C:\apache)
PHP(C:\apache\php)

-----------------------------

success!
turman at dont-spam-me dot com
10-Jun-2002 05:16
With latest PHP releases (4.2.1), compilation process doesn't produce a valid name for the Java extension library: I have to rename it to libphp_java.so in order to use it (initial name was java.so).

And on my Debian box, I have to add the following lines in my apache init.d script:
export LD_LIBRARY_PATH=/usr/local/java/jre/lib/i386
\:/usr/local/java/jre/lib/i386/classic/

It's tricky but now it works well..
gturner at newedgenetworks dot com
31-May-2002 03:20
Hello!  I have two tips about getting PHP Java to work, hopefully google will pick this up...

After you've followed the instructions (building PHP with Java enabled and hacking php.ini) and you get a message like:

  Fatal error: Cannot instantiate non-existent class: java in (file) on line (line)

That means PHP doesn't know what the 'Java' function is.  You can confirm that the Java extension isn't loaded by looking at 'phpinfo' and verifying that there is no section titled Java.   To fix this you need to edit php.ini and set the 'extensions_dir' and an 'extension' appropriately.  On our system it was 'extension_dir = /opt/php/lib/php/extensions/no-debug-non-zts-20020429' and an 'extension = java.so'.  All the documentation I found said the extension library should be called 'php_java.so', but our build produced 'java.so', I have no idea why, YMMV.

The next error message I ran into was:

  Fatal error: java.lang.UnsatisfiedLinkError: no php_java in java.library.path in (file) on line (line)

Yay! this confirms that the JVM is indeed loading (UnsatisfiedLinkError is totally on the Java side), so relax, you're almost done!  What's happening is that the Java class 'net.php.reflect' (a class in php_java.jar that is built by PHP) is trying to execute 'System.loadLibrary("php_java")' and the JVM is unable to find the file named 'libphp_java.so' (or maybe 'php_java.dll' on Windows?).  If you ever heard of LD_LIBRARY_PATH, java.library.path is the same thing.  The solution has two parts: First making sure the php.ini has a 'java.library.path' (in the '[java]' section) that's pointed at the same directory that 'extension_dir', specifically the directory containing the file 'java.so' (or maybe 'php_java.so' like everyone else).  Second, this part is bad IMHO, making a symbolic link from the ''java.so' file to 'libphp_java.so' so that Java's System.loadLibrary method can find what it's looking for (apparently Java prefixes the filename it looks for with "lib").  To make this symbolic link do 'cd' into the extensions directory and run 'ln -s java.so libphp_java.so'.

Hope somebody finds this useful!
svzn at km dot ru
22-Apr-2002 10:55
Answer to message from
praktischgek@hotmail.com
13-Feb-2002 12:26
"Java/php bridge? I used printwriter ... "
Solution looks like
out.write("var1="+URLEncoder.encode(var1));
out.write("&var2="+URLEncoder.encode(var2));
out.write("&var3="+URLEncoder.encode(var3));

etc.
venuti at sissa dot it
14-Mar-2002 04:03
Again about how to call java servlets from php...
the above method I described works as long as you don't need to send long strings as parameters and this because they are sent via GET method that cannot handle long strings. So you need to send the parameters via POST, which is not straightforward at all! Infact, you need to open a socket and write php code that sends the call to the servlet as if it came from a form with post method.
venuti at sissa dot it
04-Mar-2002 10:23
Invoking java servlet from PHP.
This might look silly, but I found many people on the net asking how to invoke a java servlet from php. Read these notes:
http://archives.neohapsis.com/archives/php/2001-03/0040.html
(look for the message about servlets).
Basically, it's like calling any other URL, so you can use the "file" function. Read also the online documentation about "file".
This solution is much easier than many others I have found around the net.
not_contactable at yahoo dot com
04-Mar-2002 03:16
Installation of PHP's Java module under Win32(Apache/IIS).

I install php in "C:\php", firstly I install with "php-4.1.1-installer.exe"(from http://www.php.net/downloads.php), and then unzip the "php-4.1.1-Win32.zip"(from http://www.php.net/downloads.php) to the C:\PHP.(because all the extension dll files are from this zip file, including php_java.dll)

I also install my Java v1.3 in "C:\jdk1.3"

And My Program require JDBC connection of the Java Program, so I did install also the JDBC driver for MySQL in "c:\JDBC4mysql\mm.mysql.jdbc-1.2c"(from http://www.mysql.com/Downloads/Contrib/mm.mysql.jdbc-1.2c.tar.gz).

About the PHP.ini:
1> You need to set the extension_dir="c:\php\extensions"(directory of all the extensions dll files)

2> Add those lines at the end of php.ini
======
[Java]
extension=php_java.dll
java.class.path="c:\php\java\php_java.jar;c:\wwwroot; c:\JDBC4mysql\mm.mysql.jdbc-1.2c"
java.home="c:\jdk1.3\bin"
java.library="c:\jdk1.3\jre\bin\hotspot\jvm.dll"
java.library.path="c:\php\extensions"
======

* extension: it is the DLL you wish to load in, here we want to load the java module.
* java.class.path: By default, you need to include the "C:\php\java\php_java.jar" for Java & PHP connection, AND those directories that contain the Java class files you wish to run. Here, my program Java classes are in "c:\wwwroot\", and ALSO the JDBC driver classes in "c:\JDBC4mysql\mm.mysql.jdbc-1.2c", because my Program need to import it.
* java.home: the bin directory (directory of java.exe)
* java.library: jvm.dll is supposed to be under JDK's jre\bin\hotspot, but sometimes it doesn't, try to Find(Start->Find) jvm.dll where it is.
* java.library.path: which is the same as the extensions directory.
christian at wenz dot org
08-Feb-2002 08:36
JDK1.4 RC is out, here are my Windows settings that make the Java extension work:

extension=php_java.dll
[Java]
java.class.path = c:\php\java\php_java.jar
java.home = d:\jdk1.4\jre
java.library = d:\jdk1.4\jre\bin\server\jvm.dll

I have not tested (yet) whether installing just the JRE works; for servlet support w/ Tomcat you do need JDK since Tomcat needs tools.jar that is not part of JRE.
ywliu at _spam_me_not_ dot hotmail dot com
30-Jan-2002 03:13
Hello,

There are two more useful links on phpbuilder.com in the PHP&JAVA discussion. They are related to the PHP and Java integration on Unix/Linux.

My settings (see above) is like that in the 1st link.

http://www.phpbuilder.com/annotate/message.php3?id=1009175
http://www.phpbuilder.com/annotate/message.php3?id=1008864

Moreover, I have the path to java in my PATH env. variable, so MAYBE its why my libjava.so works.  I couldn't find the origin of libjava.so, but now looks there are libjava.so and libjvm.so two options.

I built my php from the source package, and libphp_java.so does exist, at least on my RH6.2 with Apache 1.3.19 and Sun JDK 1.3.1.  libphp_java.so should be found under php-4.1.1/ext/java/.libs .

If you want to find some more discussion about PHP & Java integration, you may try  www.phpbuilder.com and look for php&java. It's a good place to start with.

Yen-Wei Liu
punjabimale at rediffmail dot com
26-Jan-2002 07:09
But php 4.1.1 isn't creating any libphp_java.so file even after using --with-java=/usr/java/j2sdk1.40 option.
/usr/java/j2sdk1.4.0/bin is in path.
fernando at lozano dot eti dot br
25-Jan-2002 07:20
I managed to get it working with IBM Java SDK 1.3.0 but it was not easy. Here's my php.init:

[Java]
extension = libphp_java.so
java.library.path = /usr/local/lib/php/extensions/no-debug-non-zts-20010901
java.class.path = /usr/local/lib/php/php_java.jar
java.home = /opt/IBMJava2-13
java.library = /opt/IBMJava2-13/jre/bin/classic/libjvm.so

Besides, I had to edit the httpd init.d script to include the statement:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/IBMJava2-13/jre/bin:\
/opt/IBMJava2-13/jre/bin/classic

I guess java.library.path should serve for this, but it didn't worked.
24-Jan-2002 10:13
I agree Xavier.
My php.ini settings is:
 [java]
 java.class.path = /usr/local/etc/php4/ext/java/php_java.jar
 java.home = /usr/local/jdk1.3.1_02
 java.library = /usr/local/jdk1.3.1_02/jre/lib/i386/hotspot/libjvm.so
 extension_dir = /usr/local/etc/php4/modules
 extension = libphp_java.so

When I set java.library=libjava.so and java.library.path, it doesn't work. Maybe this will help the later.
BTW.
I found the PHP4.1.0 and PHP4.1.1 cann't generate libphp_java.so, if it happen to you, you can use PHP4.0.6.

Jonathan
12-Jan-2002 02:25
About the java configuration in php.ini, setting java.library to the location of libjava.so, doesn't work for me. It only works when I set it to the location of libjvm.so. I hope this helps.

Xavier
ywliu at _spam_me_not_ dot hotmail dot com
08-Jan-2002 07:41
Hi all,
After struggling for some time and referring to numerous confusing articles , I finally came up with a working Java section in php.ini, for Linux (RedHat 6.2) with Apache 1.3.22 and Sun JDK 1.3.1.

[Java]
java.class.path=/usr/local/lib/php/php_java.jar:/home/sinanet/www
java.home = /usr/java
java.library=libjava.so
extension_dir=/usr/local/lib/php/extensions/no-debug-non-zts-20010901
extension=libphp_java.so

Please substitute your document root for /home/sinanet/www , and your extension_dir (it varies from version to version ) to libphp_java.so for extension_dir here.

I have tried this configuration with php 4.0.6, 4.1.0, and 4.1.1. It works pretty well. And I think this may save some of your time to look for a working [Java] section.

Yen-Wei Liu
Magnus_Naeslund at nowhere dot to dot be dot found
25-Dec-2001 01:52
An _very_ important thing here is to remember that the apache must be linked with pthreads (do "LDFLAGS=-lpthread ./configure <options>", or like me, add it the the .spec file).
You can check if your apache is pthreaded with "ldd $(which httpd)" if you like.
I experianced a lot of hangs/errors due to this problem, it's a shame that it's not in the docs / README (i didn't find it).

Magnus
ard(at)ard dot nu at remove dot thispart
19-Nov-2001 04:26
If you get the 'Couldn't create Virtual Machine' error without any further explanation, you could try and add the following setting to Apache's environment.

LD_LIBRARY_PATH=/usr/lib/j2sdk1.3/jre/lib/i386/classic:/usr/lib/j2sdk1.3/jre/lib/i386

(Running Debian 2.2 / Apache 1.3.19 / PHP 4.0.6 / Blackdown JDK 1.3.1)
emilebosch at hotmail dot com
19-Oct-2001 03:19
Hey ppl,
i got this link for a friend, you can get more information on the PHP and JAVA topic here :-)

http://www.onlamp.com/pub/a/php/2001/06/14/php_jav.html

Warm regards,
Emile Bosch

<ircg_whoisjava_last_exception_clear>
 Last updated: Thu, 21 Aug 2003
show source | credits | sitemap | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: http://php.mirrors.ilisys.com.au/
Last updated: Sat 01 Nov 2003 04:13:36 EST EST