title: Java HTTP Php Server
body: <p>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!</p>
  
  <p>My Code so far:</p>
  
  <pre><code>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(() -&gt; 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(() -&gt; {
              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() &gt; 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() &amp;&amp; st.nextToken().equalsIgnoreCase("GET") &amp;&amp; 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("..") &gt;= 0 || filename.indexOf(':') &gt;= 0 || filename.indexOf('|') &gt;= 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)) &gt; 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"
                          + "&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;" + filename + " not found&lt;/body&gt;&lt;/html&gt;\n");
                  out.close();
              }
          } catch (IOException x) {
              System.out.println(x);
          }
      }
  }
  </code></pre>
  
  <p>(Stackoverflow doesnt likes that many code... Thats why i have this external Link...)</p>