<?php
// port_process_info.php
// RJM Programming
// January, 2016
// What process uses a designated port
// Thanks to http://stackoverflow.com/questions/1482260/how-to-get-the-os-on-which-php-is-running

$gp = 'nowayjose';
if (isset($_GET['port'])) $gp = $_GET['port'];
if (isset($_POST['port'])) $gp = $_POST['port'];
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    // echo 'This is a server using Windows!';
    exec('netstat -ano | findstr ":' . $gp . ' PID" > ppi.txt');
} else {
    // echo 'This is a server not using Windows!';
    exec('sh -c "lsof -i:' . $gp . '" > ppi.txt');
}
echo "<!doctype html><html><body style='background-color: yellow;'><div align='center'>";
if (str_replace(" ","",file_get_contents("ppi.txt")) == "" && ($gp == 'nowayjose' || $gp == '')) {
  echo ""; // <!doctype html><html><body><h1>What process uses a designated port?</h1><br><br><form action='/port_process_info.php' method='GET'>Port: <input name='port' id='port' type=number value='80' title='Port of interest' step=1></input><br><br><input type='submit' value='Show Processes Using This Port'></input></form></body></html>";
  $gp = "80";
} else if (str_replace(" ","",file_get_contents("ppi.txt")) == "") {
  echo "<div align='left' style='background-color: white; border: 10px solid orange;'>That port " . $gp . " has no activity associated with it.</div><br><br>";
} else {
  echo "<div align='left' style='background-color: white; border: 10px solid orange;'>" . str_replace("\n", "<br>", file_get_contents("ppi.txt")) . "</div><br><br>";
}
echo "<h1>What process uses a designated port?</h1><br><br><form action='./port_process_info.php' method='GET'>Port: <input name='port' id='port' type=number value='" . $gp . "' title='Port of interest' step=1></input><br><br><input style='background-color: lightgray;' type='submit' value='Show Processes Using This Port'></input></form></div></body></html>";

?>