


Detailed explanation of how php calls its own java program, detailed explanation of how php calls java_PHP tutorial
Jul 12, 2016 am 08:51 AMDetailed explanation of how PHP calls its own Java program, Detailed explanation of how PHP calls its own Java program
The example in this article describes the implementation method of PHP calling its own Java program. Share it with everyone for your reference, the details are as follows:
It goes without saying that I need to install jdk at the beginning. I installed java ee 5 jdk
1. Unzip the downloaded php-java-bridge_5.2.2_j2ee.zip. There is a JavaBridge.war and open it directly with winrar. Go to WEB-INF/lib/JavaBridge.jar and copy this jar package to the ext/ directory of your php directory.
2. Open the war package, there is a java folder inside, copy it all to your PHP project, such as /demo/java
3. The current version is VMBridge. If you want PHP to call the java class, you must first start JavaBridge,
Call java –jar JavaBridge.jar from the command line or double-click JavaBridge.jar and select listening port 8080 in the pop-up window
For easy startup in the future, I created a new bat file under ext/ with the following content:
@echo off start javaw -jar JavaBridge.jar
After saving, double-click to start. There will be a prompt box to select vmbridge port. The default is 8080. Just click ok
4. Create a new test.php under /demo/ with the following content:
<?php require_once("java/Java.inc"); header("content-type:text/html; charset=utf-8″); // get instance of Java class java.lang.System in PHP $system = new Java('java.lang.System'); $s = new Java("java.lang.String", "php-java-bridge config…<br><br>"); echo $s; // 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')); ?>
5. Start apache and view http://localhost/demo/test.php in the browser
You will see the following information:
Copy code The code is as follows: php-java-bridge config…
Java version=1.6.0_10
Java vendor=Sun Microsystems Inc.
OS=Windows Vista 6.0 on x86
Sunday, November 23, 2008 at 4:31:49 PM China Standard Time
Custom JAR:
package ttt; public class phptest{ /** * A sample of a class that can work with PHP * NB: The whole class must be public to work, * and of course the methods you wish to call * directly. * * Also note that from PHP the main method * will not be called */ public String foo; /** * Takes a string and returns the result * or a msg saying your string was empty */ public String test(String str) { if(str.equals("")) { str = "Your string was empty. "; } return str; } /** * whatisfoo() simply returns the value of the variable foo. */ public String whatisfoo() { return "foo is " + foo; } /** * This is called if phptest is run from the command line with * something like * java phptest * or * java phptest hello there */ public static void main(String args[]) { phptest p = new phptest(); if(args.length == 0) { String arg = ""; System.out.println(p.test(arg)); }else{ for (int i = 0; i < args.length; i++) { String arg = args[i]; System.out.println(p.test(arg)); } } } }
Generate it as JAR and copy it to the D drive.
/demo/index2.php
<? require_once("java/Java.inc"); java_require("D://1.jar"); $myj = new Java("ttt.phptest"); echo "Test Results are <b>" . $myj->test("Hello World") . "</b>"; $myj->foo = "A String Value"; echo "You have set foo to <b>" . $myj->foo . "</b><br>\n"; echo "My java method reports: <b>" . $myj->whatisfoo() . "</b><br>\n"; ?>
View http://localhost/demo/index2.php in your browser
Method 2: php_java.dll needs to configure php.ini, the new version of php-java-bridge does not have dll files
First make sure that your PHP and Apache servers and JDK (or JRE are also acceptable) have been installed
Download php-java-bridge online (find it yourself or http://sourceforge.net/project/showfiles.php?group_id=117793)
Decompress the downloaded php-java-bridge. After decompression, there will be a JavaBridge.war in the folder. Then decompress this JavaBridge.war in the same way (win rar can decompress it)
After decompression, you can find java-x86-windows.dll from the cgi folder in the WEB-INF folder, and JavaBridge.jar
Copy java-x86-windows.dll and JavaBridge.jar to the PHP plug-in folder (in my case it is C:/AppServphp/ext), and change java-x86-windows.dll to php_java.dll
Modify php.ini file
If php.ini does not originally have the following content, please add it yourself. If it originally has the following content, please modify it to the following [I am using JDK]
extension=php_java.dll
[Java] ;java.java = "C:\jdk1.6.0_13\bin\java" java.class.path = "D:\php\ext\JavaBridge.jar;c:\myclasses" c:\myclasses可自定義,用來存放自己寫的JAVA文件 java.java_home = "C:\jdk1.6.0_13\jre" java.library = "d:\jdk1.2.2\jre\bin\server\jvm.dll" java.library.path = "D:\php\ext"
Restart Apache and check phpinfo
java java support Enabled java bridge 3.0.8 java.java_home C:\jdk1.6.0_13 java.java C:\jdk1.6.0_13\bin\java java.log_file <stderr> java.log_level no value (use backend's default level) java.ext_java_compatibility Off java command C:\jdk1.6.0_13\bin\java -Djava.library.path=D:\php\ext -Djava.class.path=D:\php\ext/JavaBridge.jar -Djava.awt.headless=true php.java.bridge.JavaBridge INET_LOCAL:0 2 java status running java server 9267
Check whether the second to last item, java status, is not running (this is because you have not started JavaBridge.jar). If it changes to running <—- it means JavaBridge.jar has been started and php-java-bridge can be officially used
Execute if not started:
Because it is impossible to manually start JavaBridge.jar every time you turn on the computer
So we write a batch process with the following content
@echo off start javaw -jar JavaBridge.jar
Save it as phpJavaBridge.bat and also put it in the PHP plug-in folder (here is C:AppServ/php/ext)
Create a shortcut for the file and put the created shortcut into startup (here is C:/Documents and Settings/All Users/"Start"/Menu/Program Startup)
In this way, phpJavaBridge.bat in the C:AppServphpext folder will be automatically launched every time the computer is turned on
Simple example
<? $system=new Java('java.lang.System'); echo "java版本".$system->getProperty('java.version')."<BR>"; echo "發(fā)行廠商".$system->getProperty('java.vendor')."<BR>"; echo "作業(yè)系統(tǒng)版本".$system->getProperty('os.name')."<BR>"; echo "java版本".$system->getProperty('os.version')."<BR>"; echo "java版本".$system->getProperty('os.arch')."<BR>"; ?>
Or find test.php in php-java-bridge and check the effect at http://localhost/test.php
<?php $system=new Java("java.lang.System"); print "Java version=".$system->getProperty("java.version")." <br>"; ?>
[java] extension=PHP_java.dll java.library.path=c:webPHP4extensions java.class.path="c:webPHP4extensionsjdk1.2.2PHP_java.jar;c:myclasses"
Add extension=PHP_java.dll to PHP.INI, and in [java], set java.class.path so that it points to PHP_java.jar. If you use the new JAVA class, you should also save Enter this path. In this example, we use the c:myclasses directory.
Test the environment and create the following PHP file:
<?php $system = new Java("java.lang.System"); print "Java version=".$system->getProperty("java.version")." <br>n"; print "Java vendor=".$system->getProperty("java.vendor")." <p>nn"; print "OS=".$system->getProperty("os.name")." ". $system->getProperty("os.version")." on ". $system->getProperty("os.arch")." <br>n"; $formatter = new Java("java.text.SimpleDateFormat","EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz"); print $formatter->format(new Java("java.util.Date"))."n"; ?>
If you installed it correctly, you will see the following message:
Copy code The code is as follows: Java version=1.2.2
Java vendor=Sun Microsystems Inc.
OS=Windows 95 4.10 on x86
Wednesday, October 18, 2000 at 10:22:45 AM China Standard Time
It is important to understand how to call JAVA. The next step is to create your own JAVA file and let PHP call it. The java.class.path of the JAVA file is very important
Create and use your own JAVA classes [Note case]
Creating your own JAVA classes is easy. Create a new phptest.java file and place it in your java.class.path directory [c:myclasses]. The file content is as follows:
public class phptest{ /** * A sample of a class that can work with PHP * NB: The whole class must be public to work, * and of course the methods you wish to call * directly. * * Also note that from PHP the main method * will not be called */ public String foo; /** * Takes a string and returns the result * or a msg saying your string was empty */ public String test(String str) { if(str.equals("")) { str = "Your string was empty. "; } return str; } /** * whatisfoo() simply returns the value of the variable foo. */ public String whatisfoo() { return "foo is " + foo; } /** * This is called if phptest is run from the command line with * something like * java phptest * or * java phptest hello there */ public static void main(String args[]) { phptest p = new phptest(); if(args.length == 0) { String arg = ""; System.out.println(p.test(arg)); }else{ for (int i = 0; i < args.length; i++) { String arg = args[i]; System.out.println(p.test(arg)); } } } }
After creating this file, we need to compile this file and use the javac phptest.java command on the DOS command line.
In order to use PHP to test this JAVA class, we create a phptest.php file in the web directory with the following content:
<?php $myj = new Java("phptest"); echo "Test Results are <b>" . $myj->test("Hello World") . "</b>"; $myj->foo = "A String Value"; echo "You have set foo to <b>" . $myj->foo . "</b><br>\n"; echo "My java method reports: <b>" . $myj->whatisfoo() . "</b><br>\n"; ?>
如果你得到這樣的警告信息:java.lang.ClassNotFoundException error ,這就意味著你的 phptest.class 文件不在你的 java.class.path 目錄下。
注意的是 JAVA 是一種強制類型語言,而 PHP 不是,這樣我們在將它們融合時,容易導致錯誤,于是我們在向JAVA傳遞變量時,要正確指定好變量的類型。如:$myj->foo = (string) 12345678; or $myj->foo = "12345678″;
這只是一個很小的例子,你可以創(chuàng)建你自己的 JAVA 類,并使用 PHP 很好的調用它!關鍵在于理解java.class.path目錄的重要性。
更多關于PHP相關內容感興趣的讀者可查看本站專題:《PHP數組(Array)操作技巧大全》、《php排序算法總結》、《PHP常用遍歷算法與技巧總結》、《PHP數據結構與算法教程》、《php程序設計算法總結》、《PHP數學運算技巧總結》、《php正則表達式用法總結》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

Execution of SELECT queries using PHP's preprocessing statements can effectively prevent SQL injection and improve security. 1. Preprocessing statements separate SQL structure from data, send templates first and then pass parameters to avoid malicious input tampering with SQL logic; 2. PDO and MySQLi extensions commonly used in PHP realize preprocessing, among which PDO supports multiple databases and unified syntax, suitable for newbies or projects that require portability; 3. MySQLi is specially designed for MySQL, with better performance but less flexibility; 4. When using it, you should select appropriate placeholders (such as? or named placeholders) and bind parameters through execute() to avoid manually splicing SQL; 5. Pay attention to processing errors and empty results to ensure the robustness of the code; 6. Close it in time after the query is completed.

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)->

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana
