10

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 negative or positive number.

I want to execute this script from Java code(J2EE) and store that result in some object.

I'm trying to use httpURLConnection for that. I establish a connection but can not fetch the result. I'm not sure if I execute the script at all.

4
  • 2
    So what exactly goes wrong? We want error messages... Commented Mar 17, 2009 at 19:10
  • > Any help would be appreciated; > I'm not sure if I execute the script at all. Check your web server logs to see if it is being executed, and if so what the errors are. Useless without these. Commented Mar 17, 2009 at 19:11
  • there is no error messages,I just didn't know how to fetch the result Commented Mar 18, 2009 at 7:57
  • 1
    please fix your question as it is not related to php(like 'how to write REST client in java)'). Because it seems it is about how to run php script from classpath/filepath from java and it is not. Commented Jun 24, 2016 at 8:59

6 Answers 6

14
public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL yahoo = new URL("http://www.yahoo.com/");
        URLConnection yc = yahoo.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                yc.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}

This snippet is from the offical Java tutorial (http://java.sun.com/docs/books/tutorial/networking/urls/readingWriting.html). This should help you.

Sign up to request clarification or add additional context in comments.

Comments

14

If your J2EE app is deployed on the same server the PHP script is on, you can also execute it directly through as an independent process like this:

  public String execPHP(String scriptName, String param) {
    try {
      String line;
      StringBuilder output = new StringBuilder();
      Process p = Runtime.getRuntime().exec("php " + scriptName + " " + param);
      BufferedReader input =
        new BufferedReader
          (new InputStreamReader(p.getInputStream()));
      while ((line = input.readLine()) != null) {
          output.append(line);
      }
      input.close();
    }
    catch (Exception err) {
      err.printStackTrace();
    }
    return output.toString();
  }

You will pay the overhead of creating and executing a process, but you won't be creating a network connection every time you need to execute the script. I think that depending on the size of your output, one will perform better than the other.

2 Comments

I don't have PHP on the same server so this is not working for me
I tried this example but nothing gets outputted from PHP to Java.
9

If you are trying to run it over HTTP I would recommend the Apache Commons HTTP Client libraries. They make it incredibly easy to perform this type of task. For example:

    HttpClient http = new HttpClient();
    http.setParams(new HttpClientParams());
    http.setState(new HttpState());

    //For Get
    GetMethod get = new GetMethod("http://www.something.com/myscript?param="+paramVar);
    http.executeMethod(get);

    // For Post
    PostMethod post = new PostMethod("http://www.something.com/myscript");
    post.addParameter("param", paramVar);
    http.executeMethod(post);

Comments

1

On the related note if you are trying to execute a php script from a java program , you may refer the following code

        Process p = Runtime.getRuntime().exec("php foo.php");

        p.waitFor();

        String line;

        BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while((line = error.readLine()) != null){
            System.out.println(line);
        }
        error.close();

        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        while((line=input.readLine()) != null){
            System.out.println(line);

        }

        input.close();

        OutputStream outputStream = p.getOutputStream();
        PrintStream printStream = new PrintStream(outputStream);
        printStream.println();
        printStream.flush();
        printStream.close();

Comments

0

I faced exactly the same issue today. For me, that thing which worked was URLEncoding the PHP script parameters using java.net.URLEncoder.encode method.

String sURL = "myURL";
String sParam="myparameters";
String sParam=java.net.URLEncoder.encode(sParam,"UTF-8");
String urlString=sURL + sParam;     
    HttpClient http = new HttpClient();
    try {
        http.getHttpResponse(urlString);
    } catch (AutomationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    http=null;

Comments

0

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();

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.