Pyroglyph
Pyroglyph

Reputation: 179

See if a server is listening on a port in PHP?

Before answering, please note that I am completely new to PHP. I have heard it is powerful.

What I'm trying to do is have a page on my (Apache 2) web server that when a user clicks a button on the page, the server will check if a port is running on it's own IP with a preset port for each button, I want multiple buttons with the same IP but different ports to be pinged.

Example:

I already have PHP installed and working, all I need is some code :)

Upvotes: 0

Views: 3577

Answers (1)

andrew
andrew

Reputation: 9593

Attempt a connection on the port and return the result:

 <?php
     function Connect($port) {
        $serverConn = @stream_socket_client("tcp://127.0.0.1:{$port}", $errno, $errstr);
        if ($errstr != '') {
            return false;
        }
       fclose($serverConn);
       return true;
      } 


    if(isset($_POST['portTest'])){
       switch ($_POST['portTest']){
           case 'minecraft': $port= '25565';
        break;
           case 'Terraria': $port= '7777';
        break;  
           default: exit;
       }
     if (Connect($port)){
         echo "Server is running!";
       }else{
         echo "Server is down";
       }
    }
    ?> 

    <form method="POST">
    <input type="submit" name="portTest" value="minecraft">
    <input type="submit" name="portTest" value="Terraria">
    </form>

Upvotes: 2

Related Questions