title: Check if anything is listening in a port in PHP
body: <p>I want to use PHP to check if anything is listening to <code>localhost:81</code>, to ensure that is available for a PHP built in server to run on. </p>
  
  <p>i.e. I want to check if the following would run properly <code>php -S localhost:81</code>. </p>
  
  <p>Now if something is already listening on port 81 (e.g. Apache), this will of course cause problems.</p>
  
  <p>I read the following: <a href="https://stackoverflow.com/questions/10127691/how-can-i-check-if-ports-465-and-587-are-open-with-php">How can I check if ports 465 and 587 are open with PHP?</a> and the solution did not seem to work.</p>
  
  <p>i.e.:</p>
  
  <pre><code>$fp = fsockopen('localhost', '81', $errno, $errstr, 5);
  var_dump($fp); // returns false
  if (!$fp) {
      // port is closed or blocked
      echo "CLOSED!";
      return false;
  } else {
      // port is open and available
      echo "OPEN!";
      fclose($fp);
      return true;
  }
  </code></pre>
  
  <p>Unfortunately the above keeps returning "CLOSED!" even though its not.</p>
  
  <p>I also get the following error message:</p>
  
  <pre><code>PHP Warning:  fsockopen(): unable to connect to localhost:81 (Connection refused)
  </code></pre>
  
  <p>How do I solve my problem?</p>
  
  <p>Is there any alternatives?</p>