How can I execute a PHP script from Java?

后端 未结 6 388
迷失自我
迷失自我 2020-12-16 03:01

I have a php script which is executed over a URL. (e.g. www.something.com/myscript?param=xy)

When this script is executed in a browser it gives a coded result, a neg

6条回答
  •  孤街浪徒
    2020-12-16 03:52

    I faced similar situation where I need to call PHP function from java code and I have used below code to achieve this. In below code "/var/www/html/demo/demo.php" is the PHP file name and callToThisFunction() is the PHP function name. Hope this helpful for someone.

    public static void execPHP() {
    
            Process process = null;
    
            try {
    
                process = Runtime.getRuntime().exec(new String[]{"php", "-r", "require '/var/www/html/demo/demo.php'; callToThisFunction();"});
    
                process.waitFor();
    
                String line;
    
                BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    
                while ((line = errorReader.readLine()) != null) {
                    System.out.println(line);
                }
    
                errorReader.close();
    
                BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    
                while ((line = outputReader.readLine()) != null) {
                    System.out.println(line);
    
                }
    
                outputReader.close();
    
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            OutputStream outputStream = process.getOutputStream();
            PrintStream printStream = new PrintStream(outputStream);
            printStream.println();
            printStream.flush();
            printStream.close();
    
        }
    

提交回复
热议问题