>PHP: Integración de Java y PHP - Manual

MANUAL DE PHP

(y algo mas)windsurf pozo izquierdo
Google
search for in the  
ELMARRAJO.COM mysql bulma desarrollo web linux fedora html ayuda

windsurf mercedes camper

LXIV. Integración de Java y PHP

Introducción

Existen dos formas diferentes de integrar PHP y Java: en primer lugar, se puede integrar PHP dentro de un entorno de ejecución de servlets de Java, que en estos momentos es una solución más estable y más eficiente. La segunda opción es la de integrar Java dentro de PHP. La primera forma de integración se realiza a traves de un módulo SAPI que actua como interfaz del servidor de servlets. La segunda forma se realiza mediante esta extensión de Java.

Esta extensión de Java proporciona de forma sencilla los medios necesarios para crear e invocar métodos sobre objetos de Java desde PHP. La JVM se crea utilizando JNI y todo se ejecuta en un unico proceso.

Aviso

Esta extensión es EXPERIMENTAL. Esto significa que el comportamiento de esta extensión, los nombre de sus funciones y en definitiva TODO lo documentado sobre esta extensión, puede cambiar en una futura versión de PHP SIN AVISO. La advertencia queda hecha, y utilizar esta extensión queda bajo su propia responsabilidad.

Requisitos

Para utilizar esta extensión es necesario disponer de una máquina virtual Java (JVM) instalada en el sistema.

Instalación

Esta extension PECL no esta ligada a PHP.

En PHP 4 la fuente de las extensiones PECL pueden encontrarse en el directorio ext/ que se existe en las fuentes de PHP o en el enlace PECL de arriba. Para incluir el soporte de Java en PHP, es necesario añadir el parámetro --with-java[=DIR] a las opciones de configuración de PHP, donde DIR apunta al directorio base de instalación del JDK. Esta extensión solamente puede ser construida como un módulo compartido. En el archivo php-src/ext/java/README se incluye mas información sobre como construir esta extensión.

Los usuarios de Windows deben activar la opción php_java.dll en el fichero php.ini para poder utilizar estas funciones. En PHP 4, esta DLL se encuentra en el directorio extensions/ que existe en los binarios de PHP para Windows. Podeis descargar esta DLL de las extensiones PECL desde la pagina PHP Downloads o desde http://snaps.php.net/.

Nota: Para poder trabajar con este módulo en un entorno Windows con una versión de PHP <= 4.0.6, se debe hacer accesible el archivo jvm.dll desde el PATH del sistema. Para versiones de PHP > 4.0.6 no es necesario realizar esta operación.

Configuración en tiempo de ejecución

El comportamiento de estas funciones está afectado por los valores definidos en php.ini.

Tabla 1. Opciones de configuració de Java

NombreValor por defectoDonde se cambiaRegistro de cambios
java.class.pathNULLPHP_INI_ALL 
java.homeNULLPHP_INI_ALL 
java.library.pathNULLPHP_INI_ALL 
java.libraryJAVALIBPHP_INI_ALL 
For further details and definitions of the PHP_INI_* constants, see the Apéndice G.

Tipos de recursos

Esta extensión no tiene ningún tipo de recurso definido.

Constantes predefinidas

Esta extensión no tiene ninguna constante definida.

Ejemplos

Ejemplo 1. Ejemplo de Java

<?php
 
// se obtiene la instancia de la clase de Java java.lang.System desde PHP
 
$system = new Java('java.lang.System');

 
// ejemplo de acceso a las propiedades de Java
 
print 'Version de Java='.$system->getProperty('java.version').' <br>';
  print
'Desarrollador de la JVM=' .$system->getProperty('java.vendor').' <br>';
  print
'Sistema Operativo='.$system->getProperty('os.name').' '.
            
$system->getProperty('os.version').' on '.
            
$system->getProperty('os.arch').' <br>';

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

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

Ejemplo 2. Ejemplo de AWT

<?php
 
// Este ejemplo solo puede ser ejecutado como CGI.

 
$frame  = new Java('java.awt.Frame', 'PHP');
 
$button = new Java('java.awt.Button', 'Hola Mundo de Java!');

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

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

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

  • new Java() crea una nueva instancia de una clase solamente si existe un constructor adecuado. Si no se le pasan parámetros, debe existir un constructor por defecto adecuado, como por ejemplo en el caso de java.lang.System que permite el acceso a la mayoría de sus funcionalidade a través de metodos estáticos.

  • Al acceder a los miembros de una instancia, en primer lugar se buscarán las propiedades del bean y en segundo lugar los miembros publicos. En otras palabras, print $date.time se intentará resolver en primer lugar como $date.getTime() y posteriormente como $date.time.

  • Tanto los miembros estáticos como los miembros de una instancia de un objeto pueden ser accedidos utilizando la misma sintaxis. Ademas, si el objeto es de tipo java.lang.Class, entonces se puede acceder a los miembros estaticos de la clase (tanto los atributos como los metodos).

  • Las excepciones que se lanzan durante la ejecución se transforman en avisos de tipo "warning" de PHP y en resultados de tipo NULL. Los avisos de tipo "warning" se pueden eliminar añadiendo el prefijo "@" a la llamada del metodo. Las siguientes funciones de la API se pueden utilizar para obtener y borrar el ultimo error surgido:

  • La resolución de la sobrecarga es uno de los problemas mas dificiles de resolver dadas las grandes diferencias entre PHP y Java en el tema del "tipado" de las variables. Esta extensión utiliza un metodo simple pero muy efectivo para determinar cual es la mejor decisión a tomar cuando se produce la sobrecarga.

    Ademas, los nombres de los métodos en PHP no distinguen entre mayusculas y minusculas, por lo que se aumenta elnúmero de posibilidades para elegir en las situaciones de sobrecarga.

    Una vez seleccionado el método, los parámetros se transforman si es necesario, incluso con la posibilidad de perder datos (por ejemplo, los números de tipo "double" se transforman en tipo boolean) (Nota del traductor: esta conversion parece totalmente absurda, asi que puede tratarse de un fallo de la documentación de la version original).

  • En PHP, las variables de tipo "array" y "hashtable" pueden ser utilizadas de forma indistinta. En PHP, las hashtables solo pueden incluir en las claves variables de tipo integer o string. Ademas, en Java los arrays cuyas variables son de algun tipo primitivo, no pueden contener huecos. Por ultimo, se debe recordar que este tipo de variables se pasan por valor, por lo que pueden llegar a consumir una cantidad apreciable de memoria y de tiempo.

SAPI de los servlets Java

Basandose en el mismo mecanismo que la extension de Java de PHP, la SAPI de los servlets Java permite ejecutar PHP como un servlet de Java. La ventaja más significativa de esta forma de actuar es que se aprovechan las características de "pooling" y de reutilización de recursos implementadas por la mayoría de servidores que permiten ejecutar servlets. El archivo php4/sapi/README contiene las instrucciones necesarias para compilar el modulo SAPI para los servlets Java. Notas:

  • Aunque, en principio, este código podría ser ejecutado en cualquier servidor que permita la ejecución de servlets, solo se ha probado en el servidor Jakarta/Tomcat desarrollado por la fundación Apache. Por ese motivo, cualquier información sobre la forma de ejecutarlo en otros servidores, los errores encontrados, las soluciones planteadas, etc...sera una información muy apreciada y que animamos a que los desarrolladores envien a los responsables del desarrollo del proyecto PHP.

  • Se pueden producir conflictos entre PHP y SAPI con respecto al directorio de trabajo. Mientras PHP se está ejecutando, el servidor de servlets no podrá cargar ninguna clase que se encuentre en el CLASSPATH si su ruta se especifica de forma relativa y tampoco podrá encontrar el directorio de trabajo utilizado para las tareas de administración y compilación de JSP.

Tabla de contenidos
java_last_exception_clear -- Borra la última excepción de Java
java_last_exception_get -- Obtiene la última excepción de Java


add a note add a note User Contributed Notes
Integración de Java y PHP
frey_thom76 at yahoo dot de
21-Apr-2006 06:16
The previous note is very misleading:

Switching from the Apache- to the CGI SAPI doesn't solve the fundamental problem that PHP4's ext/php_java continously allocates a new VM until the machine runs out of resources ("Fatal error: Unable to Create Java Virtual Machine")

The mentioned JavaBridge works well with PHP 4 (I use it since one year now)

It is not necessary to switch to Apache 2 to run PHP 4 and PHP 5 side-by-side
tobozo at phpsecure dot info
19-Apr-2006 08:06
Workaround for Win32 / Apache / PHP4 users that do not wish to switch from SAPI to CGI :

Java Bridge is a great project, and it's too bad I *have* to upgrade to php5 to see it working. One more reason not to use php5.

I have a production server running a few intranet applications and other php utilities, on a w2k platform with Apache-1.3.33 and php-4.3.10.

I need to have java working along with php on this production server, and I do not wish to upgrade all php applications to php5, nor do I wish to switch to Apache2 to get php4 and php5 running together.

So my choice went to ext/php_java. Of course I've had the usual issues  ...

"Fatal error: Unable to Create Java Virtual Machine"

Basically the workaround for this thread issue is to " use CGI instead of SAPI "

But CGI is slower than SAPI, what about performances for all my applications ?

Well there is a (clumsy) solution :  use both CGI and SAPI, keeping SAPI for the regular php work, and creating a new mime type and extension in the httpd.conf for the php files invoking java.

I chose to use the '.jhp' extension (yeah, sounds horrible but still, it's nicer than '.phava'), here's a copy of my settings :

my php.ini :
--------------
[Java]
extension=php_java.dll
java.class.path = C:\php4-Win32\extensions\php_java.jar
java.home = c:\jdk-1.5
java.library = c:\jdk-1.5\jre\bin\server\jvm.dll

my httpd.conf :
------------------
ScriptAlias /jhp/ "C:/php4-Win32/"
AddType application/x-httpd-jhp .jhp
Action application/x-httpd-jhp /jhp/php.exe

The Server :
--------------
Windows 2000 (fr) SP4
Apache/1.3.33 (Win32)
Php 4.3.10 (SAPI + CGI)
Java version=1.5.0_06
11-Mar-2006 10:33
For those who want to run php with a recent tomcat version, you'll need the following patch:

http://wiki.apache.org/tomcat/UsingPhp
meaton53 at hotmail dot com
08-Mar-2006 11:46
I just wanted to post this for people that were having the same troubles that I was having.  I am running OES SuSe Linux 9-1.  I started this adventure because I needed to connect to a progress database via PHP.  And I couldn't use ODBC drivers because the progress ODBC drivers were simply to old for unixODBC and iODBC (progress 9.1c).  So I had to use JDBC with this wonderful PHP extension along with the PHP-Java Bridge found at:
http://sourceforge.net/projects/php-java-bridge
So Just for some notes, in the PHP.INI file I had to have:

extension=java.so
[java]
java.java_home=/usr/local/java
java.classpath=.:/usr/progress/dlc91c/java/progress.jar
:/usr/progress/dlc91c/java/jdbc.jar
java.libpath=.:/usr/progress/dlc91c/lib
:/usr/local/lib/php/extensions

And be careful because lots of sites tell you that the two varibles above are java.class.path, and java.library.path.

And also to be able to connect to a progress database from java in Linux you have to set your LD_ASSUME_KERNEL varible to 2.4.0 to do this simply add to you profile.local file:
export LD_ASSUME_KERNEL=2.4.0. 
If you want to know why please email me and I will tell you.
rabisultan at gmail dot com
07-Feb-2006 07:40
If you get this error

Fatal error: Unable to create Java Virtual Machine in

it can be fixed by modifying your php.ini file, you will need to add in the path to the JRE's lib folder.

My php.ini file (php4/Apache2):
java.class.path= "e:\minerva\php\extensions\php_java.jar; c:\j2sdk1.4.2_08\jre\lib; C:\j2sdk1.4.2_08"
java.home = "c:\j2sdk1.4.2_08\bin; c:\j2sdk1.4.2_08\jre\lib"
java.library = "c:\j2sdk1.4.2_08\jre\bin\server\jvm.dll"
java.library.path= "e:\minerva\PHP\extensions; c:\j2sdk1.4.2_08\jre\lib"
m mokhtar at gmail dot com
30-Oct-2005 11:03
Getting PHP JavaBridge to work with PHP5 on windows server:
====================================
1- Install Java J2EE 1.5 + JDK 1.4 (which includes application server/deploy tool/etc...)
2- download pecl-5.0.5-Win32.zip and php-java-bridge_2.0.8.zip, which will include
extra dll(s)
   - unpack pecl pkg to your extensions folder, in PHP5 its ext.
   - unpack java-Bridge to root php folder, in my case its simply C:\PHP
   Note: the java-Bridge inculdes new versions of certain files like php_java.dll
   so, it would be wise to rename your old files that came with PECL pkg for example
   file_old, to rollback at anytime.

In order to deploy/test Java-Bridge .war onto your java application server follow these steps

http://cvs.sourceforge.net/viewcvs.py/php-java-bridge/php-java-bridge/
INSTALL.WINDOWS?view=markup

Note: move JavaBridge.jar to your extensions folder. and in test.php file that came
with Java-Brdige package change line java_require("test/arrayToString.jar");
to java_require("tests.php4/arrayToString.jar");

Add the following to your php.ini file and restart server:-
java.classpath = "location of JavaBridge.jar file...i.e. to your PHP extensions folder\
JavaBridge.jar,also any other extra java files that you'll be instanciating using your php script"
java.java_home = "location of jdk\bin"
java.libpath = "location of php_java.dll file...i.e. also to your PHP extensions folder"

happy integration

Cheers!!
stanley dot turnteen at gmail dot com
31-Aug-2005 12:51
The php-java-bridge from sourceforge works great - it's stable and fast. I'm using it with the Lucene full text indexing package (http://lucene.apache.org/java/docs/index.html).
beoran at gmail dot com
25-May-2005 05:24
The php-java-bridge mentioned below is indeed the way to go. It also works fine on a php 4.3.2 Linux web server. I think I can reccomend it.
08-May-2005 02:04
<quote> JVM runs fine the first time, then broke....  </quote>

The php4 java extension is simply broken, don't use it.  I am
using the "PHP Java Bridge" for PHP5 with great success on WinNT:

http://php-java-bridge.sourceforge.net
ing dot ldf at gmail dot com
06-May-2005 11:38
Reading the other post... i can run java with php.
OS: Win 2000p
PHPDev 4.2
Java j2sdk1.4.2_01

my php.ini file is set like this:

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

I have a great doubt about this..... JVM runs fine the first time, then broke.... and send a message like this:
Fatal error: Unable to create Java Virtual Machine in localhost\pag1.php on line 37
jost2345 at yahoo dot de
31-Aug-2004 05:08
The PHP/Java bridge that has been posted some time ago is now available on sourceforge.net.  It contains several bugfixes and is meant to be used as a replacement for the expermental PHP4 java bridge.

  http://sourceforge.net/projects/php-java-bridge/

So please don't send me private e-mails anymore to obtain the sourcecode for the bridge.

PHP/5 users may want to wait for the official PHP/Java bridge, which I expect to appear in a few years when java contains the appropriate hooks.
okapi at yahoo dot com
26-Aug-2004 10:05
As mentioned prior, Zend is working to be the first of an official servlet / scripting integration. I've been testing their reference implementation that's available on the JSR 223 site and it's working pretty good. Some minor issues around the edges, but been working with one of their developers to fix it. So far, pretty good.
drgroove at myway dot com
07-Aug-2004 04:33
@ smc+phpman

Zend/PHP is likely awaiting the finalization of JSR223, which seeks to allow scripting languages a much clearer form of communication to/from Java.

http://jcp.org/en/jsr/detail?id=223

This is a joint effort between Sun & Zend, among others. PHP will be the first language supported out of this JSR effort, others (such as Perl) will follow.

 - DrGroove
Moderator, Devshed.com PHP forum
a9702466 at gmx dot net
03-Mar-2004 09:08
The Java Servlet SAPI works fine in a non-threading
environment. If you want to use threads (normal case) you
have to do several things to get it work:

- get the patched files from
  http://www.pelikan-it.com/download.html

- replace the sapi/servlet/servlet.java and
  sapi/servlet/servlet.c file by the patched files

- build the php like this
  ./configure --with-tsrm-pthreads \
   --with-servlet=/opt/resin --with-java=/opt/java \
   --prefix=/opt/php-4.3.4

The primary problem is, that the request and response
objects are stored as global instance-variables of the servlet
which will be overwritten by other threads invoking the
servlet (remember: just on servlet-object for all threads!) and
all crashes. I changed the servlet to pass the request and
response objects to the java- and native-methods (where
required) to prevent the problem.

Once you have solved this problem it works fine and needs
unlike the java-extension just one jvm.
norman at junkonline dot com
29-Feb-2004 04:16
This works fine on MacOS X (Panther). The one trick is, you need to symlink "java.so" in your php extensions directory to "libphp_java.jnilib".

Here's the relevant section from my php.ini file for anyone who needs it:

[Java]
java.class.path = "/usr/local/lib/java/php_java.jar"
java.home = "/System/Library/Frameworks/JavaVM.framework/Versions/1.4.2/Home"
java.library.path = "/usr/local/lib/php/extensions/no-debug-non-zts-20020429"
extension=java.so

You may have decided to put php_java.jar somewhere other than where I did.

For some reason, setting java.library in the ini file causes this to fail, so I left it out and things worked flawlessly without it. YMMV.
Thomas
25-Feb-2004 07:44
The documentation is missing an important note:

The PHP/JAVA bridge only works on threaded http servers such as IIS, it does NOT work on http servers such as APACHE which fork off (sub-)processes.

The reason for this is that for each new request APACHE fork()'s off a new and independed copy of itself, initializes the java VM and eventually passes control over to VM until the request is finished.  If the request is  finished, the child with the java VM go to the apache pool.

That means that after a while hundreds (up to MAX-PROCESSES) of  java VM's are in the apache pool each of them eating away up to 64MB.  The machine may sooner or later crash because it ran out of memory. (If you have luck, the bridge will not run at all because apache was not statically linked to the pthreads library).

Although another PHP/Java bridge exists that does not have this problem (do a google search for "A new PHP/JAVA module"), the java binding (used by both bridges) has also problems one must be aware of. For example if one creates a Properties() object, one will receive a reference to it and may ask this reference for its values. However, if one invokes a method that returns a Properties() object, one will receive an array of values, not a reference to the Properties() object.

In short: If you want to use java from php in IIS, you can use this bridge. BUT if you want to use java from php in APACHE, you must use a socket approach (for an example see "A new PHP/JAVA module").
georgedaswani at hotmail dot com
02-Feb-2004 02:39
I was able to compile java support in no problem and got it working sun jdk 1.4.2_03 (linux)

make sure JAVA_HOME is set

make sure LD_LIBRARY_PATH has

$JAVA_HOME/jre/lib/i386

on php.ini

[Java]
java.home = "/opt/j2sdk1.4.2_03"
java.class.path = "/opt/php/lib/php/php_java.jar:/opt/php/java-packages"
java.library.path = "/opt/php/lib/php/extensions/no-debug-zts-20020429"
extension_dir= "/opt/php/lib/php/extensions/no-debug-zts-20020429"
extension = java.so

It's import to note that APACHE 2 needs to be compiled using "PREFORK" instead of a thread based else the java stuff will work for a minute, then stop working with the following error

"PHP Fatal error:  Unable to create Java Virtual Machine"

Seems that the extension is not thread safe.
golob a with tail gimb little spot org
03-Jun-2003 06: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();
?>
raggha at hotmail dot com
13-Jan-2003 02: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édric'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 01: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
18-Dec-2002 06: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
11-Dec-2002 04: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
06-Nov-2002 04: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 03: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
30-Sep-2002 02: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 08: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
28-Aug-2002 11: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 03: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!
gturner at newedgenetworks dot com
30-May-2002 01: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!
venuti at sissa dot it
04-Mar-2002 06: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
03-Mar-2002 11: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 04: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
29-Jan-2002 11: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
fernando at lozano dot eti dot br
24-Jan-2002 03: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.
Magnus_Naeslund at nowhere dot to dot be dot found
24-Dec-2001 09: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

Citas célebres

Entre los animales que la naturaleza creó, sólo el hombre llora, sólo él es ambicioso, sólo él es sobervio, sólo él es ávaro. Sólo él es supersticioso y sólo él desea vivir mucho y hacer la sepultura en que ha de enterrarse.

Plinio el Viejo
Citas en tu mail
©Contenidos Gratis

Ilusiones Opticas
ilusion_optica_057.jpg
Contenidos Web

Chiste de... Abogados
Juicio a Satán

Dios decide llevar a Satán a los tribunales para arreglar sus cuentas pendientes de una vez para siempre. Cuando se lo dice a Satán, éste se echa a reir y le contesta:

- Pero bobo, ¿y dónde crees que vas a encontrar un abogado?
Chistes en tu mail
©ContenidosGratis

Humor Gráfico
humor_grafico_051.jpg
Contenidos Web

Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos
Cake ManiaCake Mania
Jugadores: 6835
Categoría del juego: Acción
Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero.
Rainbow WebRainbow Web
Jugadores: 2199
Categoría del juego: Puzzles
Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente.
Mahjongg FortunaMahjongg Fortuna
Jugadores: 12462
Categoría del juego: Solitarios
Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta.
Chainz 2Chainz 2
Jugadores: 6955
Categoría del juego: Puzzles
Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más.
DeliciousDelicious
Jugadores: 4405
Categoría del juego: Acción
Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues!
BookwormBookworm
Jugadores: 4568
Categoría del juego: Palabras
Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos!
ZumaZuma
Jugadores: 4976
Categoría del juego: Acción
Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás!
Jewel of AtlantisJewel of Atlantis
Jugadores: 3798
Categoría del juego: Puzzles
Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis.
Jewel QuestJewel Quest
Jugadores: 3727
Categoría del juego: Puzzles
Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos!
Bejeweled 2Bejeweled 2
Jugadores: 3659
Categoría del juego: Puzzles
Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca.
Contenidos gratis en tu webSiguiente >>

Fotos divertidas
fotos_increibles_0488.jpg
Contenidos Web
microrobots avion deportes riesgo recetas cocina canaria juegos online gratis moto motociclismo horoscopos naranjas valencianas surf canarias montañismo ciudades turismo postales gratis library Horoscopos Diarios Windsurf Canarias
fregadero microondas placa electrica bañopreparar camper pantalla plananevera compresor electricacamper fiat ducato camper baño quimicomampara enrollable bañocamper aire climatizadofurgoneta surf windsurffurgoneta surf windsurftelevisor furgonetas camperfurgonetas camper cama

Sudoku del día
Nivel de dificultad: Fácil



Cómo jugar:
El juego consiste en colocar los números del 1 al nueve de tal forma que no se repita el mismo número en la columna, fila y caja (bloques 3x3 enmarcados).

©Contenidos Gratis | Sudoku en tu mail
Sucedió el...

30 de agosto de 1617

Fallece Santa Rosa de Lima, por la que se celebra el "Día de la Patrona de América".
Efemérides en tu mail
©Contenidos Gratis
windsurf canarias youtube porno canarias baleares valencia madrid