Skip to content

Commit 8511996

Browse files
committed
Added functions for PHP code execution via PHP CLI '-r' argument & Code optimisation
1 parent 87c3fd8 commit 8511996

File tree

5 files changed

+110
-36
lines changed

5 files changed

+110
-36
lines changed

.idea/misc.xml

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,16 @@
22

33
JavaPHP is a lightweight Java library that permits to execute PHP code into Java so instead of using Java servlets,
44
you can just use PHP and execute it as a part of your existing Java code, does not rely on any dependencies, its fully standalone,
5-
and you can use it in a compiled .jar file or in a simple .java file without having to compile it
5+
and you can use it in a compiled .jar file or in a simple .java file without having to compile it.
66

7-
Fun fact: this library was made in like 1 day because i had no other ideas and i was bored so yeah, now this library exists.
7+
It can be used with Webservers (NanoHTTPD, Java socket, etc...) or as a part of your Java app.
88

99
### Features
10-
- PHP file execution in java
10+
- PHP file / code execution in java
1111
- Customizable error handling
1212

13-
There are not alot of features because i keep it very simple, why would i do a lot of features since its focused only on the purpose of executing PHP in Java.
13+
### Planned features
14+
- PHP file / code execution over TCP/IP using PHP-CGI
1415

1516
### How to use
1617
Simply import it to your file and do like this:
@@ -20,8 +21,6 @@ import java.io.File;
2021
import java.util.HashMap;
2122
import java.util.Map;
2223

23-
import fr.breadeater.JavaPHP;
24-
2524
public class Main {
2625
public static void main(String[] args) throws Throwable {
2726
JavaPHP javaphp = new JavaPHP(false);
@@ -33,8 +32,10 @@ public class Main {
3332

3433
javaphp.setPHPVars(env);
3534
javaphp.run(new File("./test.php").getAbsolutePath());
35+
javaphp.runWithCli("echo 'Hello World !';");
3636

3737
System.out.println(javaphp.getResult());
38+
System.out.println(javaphp.getInlineResult());
3839
}
3940
}
4041
```
@@ -44,15 +45,12 @@ Simply download the .jar / .java file from the repository Releases and import it
4445
For Maven or Gradle, add it to your local repository.
4546

4647
### Contribution
47-
You can contribute as much as you want, the conditions:
48-
- know Java.
49-
- use Java JDK 21 or later.
50-
- keep it standalone (means no external dependencies).
51-
- provide least a minimum amount of documentation to the modifications you're doing.
52-
- Make your modifications clean for readability.
53-
54-
### Contact
55-
You can contact me via [mail](mailto:contact@breadeater.fr) or send message in the discussions of the repository
48+
You can contribute as much as you want, contributors will be listed in the README.
49+
50+
NOTE: Only modifications in the Java code counts as contribution.
51+
52+
### Contributors
53+
(No contributors yet)
5654

5755
### License
5856
This project is licensed under the MIT license, see [LICENSE](./LICENSE) for more infos.

pom.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
<configuration>
2222
<archive>
2323
<manifest>
24-
<mainClass>fr.breadeater.JavaPHP</mainClass>
24+
<mainClass>fr.breadeater.Main</mainClass>
2525
</manifest>
2626
</archive>
2727
<descriptorRefs>

src/main/java/fr/breadeater/JavaPHP.java

Lines changed: 93 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,19 @@
22

33
import java.io.BufferedReader;
44
import java.io.InputStreamReader;
5+
import java.util.Arrays;
56
import java.util.Map;
67
import java.util.function.Consumer;
78

89
public class JavaPHP {
9-
private Consumer<String> ERR_CALLBACK;
10-
10+
// Private immutable variables
1111
private final String PHP_BIN_PATH;
1212
private final boolean NO_PHP_WARN;
1313

14+
// Private variables
15+
private Consumer<String> ERR_CALLBACK;
1416
private Map<String, String> env_vars;
17+
private String inlineResponse = null;
1518
private String response = null;
1619

1720
/**
@@ -75,29 +78,43 @@ public void run(String php_filepath) throws Throwable {
7578
if (!this.NO_PHP_WARN && (err.contains("PHP Warning:") || err.contains("PHP Startup:"))) onError(err);
7679
}
7780

78-
assert process != null;
81+
if (process == null){
82+
onError(new Throwable("Error while executing PHP file at " + php_filepath));
83+
return;
84+
}
7985

80-
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))){
81-
StringBuilder resBuilder = new StringBuilder();
82-
String line;
86+
this.response = processOutputHandler(process);
87+
}
8388

84-
while ((line = reader.readLine()) != null) resBuilder.append(line).append("\n");
89+
/**
90+
* Runs PHP code using PHP CLI '-r' argument
91+
* The result can be retrieved with {@link #getInlineResult} function.
92+
*
93+
* @param php_code The PHP Code
94+
*/
95+
public void runWithCli(String php_code) throws Throwable {
96+
ProcessBuilder processBuilder = new ProcessBuilder(this.PHP_BIN_PATH, "-r", php_code);
97+
Process process = null;
8598

86-
this.response = resBuilder.toString();
99+
if (this.env_vars != null){
100+
Map<String, String> environment = processBuilder.environment();
101+
environment.putAll(this.env_vars);
87102
}
88103

89-
try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()))){
90-
StringBuilder errorBuilder = new StringBuilder();
91-
String line;
92-
93-
while ((line = errorReader.readLine()) != null) errorBuilder.append(line).append("\n");
104+
try {
105+
process = processBuilder.start();
106+
} catch (Throwable error){
107+
String err = error.getMessage();
94108

95-
if (!errorBuilder.toString().isEmpty()){
96-
String err = new Throwable(errorBuilder.toString()).getMessage();
109+
if (!this.NO_PHP_WARN && (err.contains("PHP Warning:") || err.contains("PHP Startup:"))) onError(err);
110+
}
97111

98-
if (!this.NO_PHP_WARN && (err.contains("PHP Warning:") || err.contains("PHP Startup:"))) onError(err);
99-
}
112+
if (process == null){
113+
onError(new Throwable("Error while executing PHP code"));
114+
return;
100115
}
116+
117+
this.inlineResponse = processOutputHandler(process);
101118
}
102119

103120
/**
@@ -110,14 +127,22 @@ public void setErrorCallback(Consumer<String> cb){
110127

111128
/**
112129
* Gets the result of the executed PHP file
113-
* @return The result of the PHP file, returns null if no results
130+
* @return The result, returns null if no results
114131
*/
115132
public String getResult(){
116133
return this.response;
117134
}
118135

119136
/**
120-
* Error event listener, outputs error with System.err by default, to set custom error handler, use {@link #setErrorCallback}
137+
* Gets the result of the inline PHP code
138+
* @return The result, returns null if no results
139+
*/
140+
public String getInlineResult(){
141+
return this.inlineResponse;
142+
}
143+
144+
/**
145+
* Error event listener, outputs error with 'System.err' by default, to set custom error handler, use {@link #setErrorCallback}
121146
* @param error The error
122147
*/
123148
private void onError(String error){
@@ -128,4 +153,53 @@ private void onError(String error){
128153

129154
this.ERR_CALLBACK.accept(error);
130155
}
156+
157+
/**
158+
* Error event listener, outputs error with 'System.err' by default, to set custom error handler, use {@link #setErrorCallback}
159+
* @param error The error
160+
*/
161+
private void onError(Throwable error){
162+
String err = Arrays.toString(error.getStackTrace());
163+
164+
if (this.ERR_CALLBACK == null){
165+
System.err.println(err);
166+
return;
167+
}
168+
169+
this.ERR_CALLBACK.accept(err);
170+
}
171+
172+
/**
173+
* Handles the Output of a process and manage errors
174+
*
175+
* @param process The process
176+
* @return The Output of the process
177+
*/
178+
private String processOutputHandler(Process process) throws Throwable {
179+
String res;
180+
181+
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))){
182+
StringBuilder resBuilder = new StringBuilder();
183+
String line;
184+
185+
while ((line = reader.readLine()) != null) resBuilder.append(line).append("\n");
186+
187+
res = resBuilder.toString();
188+
}
189+
190+
try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()))){
191+
StringBuilder errorBuilder = new StringBuilder();
192+
String line;
193+
194+
while ((line = errorReader.readLine()) != null) errorBuilder.append(line).append("\n");
195+
196+
if (!errorBuilder.toString().isEmpty()){
197+
String err = new Throwable(errorBuilder.toString()).getMessage();
198+
199+
if (!this.NO_PHP_WARN && (err.contains("PHP Warning:") || err.contains("PHP Startup:"))) onError(err);
200+
}
201+
}
202+
203+
return res;
204+
}
131205
}

src/main/java/fr/breadeater/Main.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ public static void main(String[] args) throws Throwable {
1919

2020
javaphp.setPHPVars(env);
2121
javaphp.run(new File("./test.php").getAbsolutePath());
22+
javaphp.runWithCli("echo 'Hello World !';");
2223

2324
System.out.println(javaphp.getResult());
25+
System.out.println(javaphp.getInlineResult());
2426
}
2527
}

0 commit comments

Comments
 (0)