2

I have a Java App that creates a local HTTP Webserver on Port 8080. Is there any possible Way how I can use/ install Php on it? I searched on google about this but couldnt find any help..... Any Help is appreciated!

My Code so far:

package minet;

import java.util.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;

public class main {
    private static ServerSocket serverSocket;

    public static void main(String[] args) throws IOException {
        JFrame ip = new JFrame();
        JTextField field = new JTextField();
        field.setText("http://" + getIP() + ":8080");
        field.setEditable(false);
        field.setBounds(10, 10, 380, 110);
        ip.add(field);
        JButton shutdown = new JButton("Shutdown Minet");
        shutdown.setBounds(30, 120, 340, 50);
        ip.add(shutdown);
        ip.setLocationRelativeTo(null);
        ip.setSize(400, 200);
        ip.setLayout(null);
        ip.setVisible(true);
        shutdown.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Shutting down Minet...");
                field.setText("Shutting down Minet...");
                setTimeout(() -> System.exit(0), 1000);
            }
        });

        serverSocket = new ServerSocket(8080); // Start, listen on port 8080
        while (true) {
            try {
                Socket s = serverSocket.accept(); // Wait for a client to connect
                new ClientHandler(s); // Handle the client in a separate thread
            } catch (Exception x) {
                System.out.println(x);
            }
        }
    }

    public static void setTimeout(Runnable runnable, int delay) {
        new Thread(() -> {
            try {
                Thread.sleep(delay);
                runnable.run();
            } catch (Exception e) {
                System.err.println(e);
            }
        }).start();
    }

    private static String getIP() {
        // This try will give the Public IP Address of the Host.
        try {
            URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String ipAddress = new String();
            ipAddress = (in.readLine()).trim();
            /*
             * IF not connected to internet, then the above code will return one empty
             * String, we can check it's length and if length is not greater than zero, then
             * we can go for LAN IP or Local IP or PRIVATE IP
             */
            if (!(ipAddress.length() > 0)) {
                try {
                    InetAddress ip = InetAddress.getLocalHost();
                    System.out.println((ip.getHostAddress()).trim());
                    return ((ip.getHostAddress()).trim());
                } catch (Exception ex) {
                    return "ERROR";
                }
            }
            System.out.println("IP Address is : " + ipAddress);

            return (ipAddress);
        } catch (Exception e) {
            // This try will give the Private IP of the Host.
            try {
                InetAddress ip = InetAddress.getLocalHost();
                System.out.println((ip.getHostAddress()).trim());
                return ((ip.getHostAddress()).trim());
            } catch (Exception ex) {
                return "ERROR";
            }
        }
    }
}

// A ClientHandler reads an HTTP request and responds
class ClientHandler extends Thread {
    private Socket socket; // The accepted socket from the Webserver

    // Start the thread in the constructor
    public ClientHandler(Socket s) {
        socket = s;
        start();
    }

    // Read the HTTP request, respond, and close the connection
    public void run() {
        try {

            // Open connections to the socket
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintStream out = new PrintStream(new BufferedOutputStream(socket.getOutputStream()));

            // Read filename from first input line "GET /filename.html ..."
            // or if not in this format, treat as a file not found.
            String s = in.readLine();
            System.out.println(s); // Log the request

            // Attempt to serve the file. Catch FileNotFoundException and
            // return an HTTP error "404 Not Found". Treat invalid requests
            // the same way.
            String filename = "";
            StringTokenizer st = new StringTokenizer(s);
            try {

                // Parse the filename from the GET command
                if (st.hasMoreElements() && st.nextToken().equalsIgnoreCase("GET") && st.hasMoreElements())
                    filename = st.nextToken();
                else
                    throw new FileNotFoundException(); // Bad request

                // Append trailing "/" with "index.html"
                if (filename.endsWith("/"))
                    filename += "index.html";

                // Remove leading / from filename
                while (filename.indexOf("/") == 0)
                    filename = filename.substring(1);

                // Replace "/" with "\" in path for PC-based servers
                filename = filename.replace('/', File.separator.charAt(0));

                // Check for illegal characters to prevent access to superdirectories
                if (filename.indexOf("..") >= 0 || filename.indexOf(':') >= 0 || filename.indexOf('|') >= 0)
                    throw new FileNotFoundException();

                // If a directory is requested and the trailing / is missing,
                // send the client an HTTP request to append it. (This is
                // necessary for relative links to work correctly in the client).
                if (new File(filename).isDirectory()) {
                    filename = filename.replace('\\', '/');
                    out.print("HTTP/1.0 301 Moved Permanently\r\n" + "Location: /" + filename + "/\r\n\r\n");
                    out.close();
                    return;
                }

                // Open the file (may throw FileNotFoundException)
                InputStream f = new FileInputStream(filename);

                // Determine the MIME type and print HTTP header
                String mimeType = "text/plain";
                if (filename.endsWith(".html") || filename.endsWith(".htm"))
                    mimeType = "text/html";
                else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg"))
                    mimeType = "image/jpeg";
                else if (filename.endsWith(".gif"))
                    mimeType = "image/gif";
                else if (filename.endsWith(".class"))
                    mimeType = "application/octet-stream";
                out.print("HTTP/1.0 200 OK\r\n" + "Content-type: " + mimeType + "\r\n\r\n");

                // Send file contents to client, then close the connection
                byte[] a = new byte[4096];
                int n;
                while ((n = f.read(a)) > 0)
                    out.write(a, 0, n);
                out.close();
            } catch (FileNotFoundException x) {
                out.println("HTTP/1.0 404 Not Found\r\n" + "Content-type: text/html\r\n\r\n"
                        + "<html><head></head><body>" + filename + " not found</body></html>\n");
                out.close();
            }
        } catch (IOException x) {
            System.out.println(x);
        }
    }
}

(Stackoverflow doesnt likes that many code... Thats why i have this external Link...)

Milan
  • 97
  • 1
  • 12
  • actually StackOverflow prefers relevant code in question rather than external links because external links can die, making the question unusable in future – suvartheec Nov 28 '17 at 09:07
  • I see your comment - but external links aren't particularly useful as if we wanted to test code etc, it makes life easier to copy/paste direct from the site. May not be specifically for this question, but just an FYI. – achAmháin Nov 28 '17 at 09:07
  • Ok thanks... But i couldnt post the Question bc it said to much code... – Milan Nov 28 '17 at 09:07
  • Your question is misleading. Java and PHP are two different technologies, programming language. If you explain what you wanted to do then perhaps people could point you down the correct paths. – Minh Kieu Nov 28 '17 at 09:09
  • 1
    Why on earth would you want to run PHP on it? Language discussions aside: there are half a dozen actively developed webservers that support PHP that will do a much better job of anything you can come up with – Jeroen Steenbeeke Nov 28 '17 at 09:09
  • Its just for testing around... And i always programm in PHP thats why... I know there are many Hosters that have php webservers... I use on of them... – Milan Nov 28 '17 at 09:12
  • If you want to test the jar File: https://wiese2.lima-city.de/download.php – Milan Nov 28 '17 at 09:15
  • @Milan If I am clear, you just want access your website via Java application, right? – Vanguard Nov 28 '17 at 09:49

2 Answers2

8

From your question I understood that you used to use PHP as a web programing language. And you want to make an application in Java that shows some pages from PHP Web Server.

For this I think you need to include Built-in web server in your application. You just need to download it, uncompress it in your application path or wherever you want. You can find an INSTALL file in the directory. Install it as it shown, then start web server by:

$ cd path/to/built-in/php/web/server
$ php -S localhost:8000

Executing cmd commands is shown in this post. You may change port number as you want.

Another variant is you will need to include compressed Apache and PHP in your application installation package, then uncompress it, and edit config files programmatically, and after your application will be installed on some computer.

For showing pages from the PHP Web Server you just need to use WebView. An example of how to use it in Swing is shown here or you may use JavaFX directly without Swing if you want, because WebView is a part of JavaFX.

Vanguard
  • 1,336
  • 1
  • 15
  • 30
3

I cannot determine the exact problem you are facing. But, by the question, it seems that you wan to install a PHP server alongside your JAVA server.

This can be done easily, just select a different port number, while installing PHP. Any PHP server selects port 80 by default, so this in itself solves your problem. Just install any PHP server, it can be accessed via http://localhost, whereas your java server can be accessed via http://localhost:8080.

There has been a similar discussion here. Please check it out.

Penguine
  • 519
  • 6
  • 19
  • I hav a local webserver hosted by Java and on that exact Webserver i want to be able to run php files... – Milan Nov 28 '17 at 09:18
  • Thats exactly what I mentioned in the response – Penguine Nov 28 '17 at 09:19
  • You can install any run any PHP server.Just make sure, while installing, it does not reserve your java port(8080) – Penguine Nov 28 '17 at 09:20
  • How do i do it? – Milan Nov 28 '17 at 09:21
  • 1
    @Penguine the way I read the question is that he wants to have the Java server he wrote execute PHP code – Jeroen Steenbeeke Nov 28 '17 at 09:22
  • @Jeroen But thats impossible. Because Java and PHP are entirely different languages. Moreover...PHP is an interpreted lang whereas Java is a compiled lang – Penguine Nov 28 '17 at 09:23
  • And i want it to be OS independent... (Runnable on any OS) Thats why i wanted to use Java.. – Milan Nov 28 '17 at 09:23
  • 1
    @Penguine depends, you could have Java call PHP-CLI, but that's a terrible hack – Jeroen Steenbeeke Nov 28 '17 at 09:24
  • @JeroenSteenbeeke But would that work? I mean could you use Php files on that webserver then? And if yes, could you show me how i can do it? – Milan Nov 28 '17 at 09:26
  • 1
    @JeroenSteenbeeke Yes PHP-CLI can do the trick...but as you said...its a terrible hack. I still think the best way would be to make java PHP-API calls on same server(different port). – Penguine Nov 28 '17 at 09:29
  • @Milan I could, but I won't. Install PHP with a webserver it was designed for (Apache or nginx, for instance) – Jeroen Steenbeeke Nov 28 '17 at 09:34
  • @JeroenSteenbeeke why? It would be just for testing... :( – Milan Nov 28 '17 at 09:36
  • @Milan just for testing what? To test PHP you don't need Java, and having a Java server act as front for PHP-CLI is more work and less capable than simply installing PHP with a webserver it was designed for. Java will not magically make your PHP more portable than it already is (you can run it on pretty much any modern OS) – Jeroen Steenbeeke Nov 28 '17 at 09:47
  • @JeroenSteenbeeke And how do i install a local php webserver? – Milan Nov 28 '17 at 09:48
  • @Milan lots of options: https://stackoverflow.com/questions/1678010/php-server-on-local-machine – Jeroen Steenbeeke Nov 28 '17 at 09:49
  • I want to be able to have a USB Stick wich i have a Program on. And if i start that Program everyone in my local Network can access a Php Webserver wich files are stored on the USB Stick... – Milan Nov 28 '17 at 09:52