user1288533 user1288533 - 1 year ago 133
PHP Question

How can I ping a server port with PHP?

I want a PHP script which allows you to ping an IP address and a port number (

). I found a similar script but it works only for websites, not


function ping($host, $port, $timeout)
$tB = microtime(true);
$fP = fSockOpen($host, $port, $errno, $errstr, $timeout);
if (!$fP) { return "down"; }
$tA = microtime(true);
return round((($tA - $tB) * 1000), 0)." ms";

//Echoing it will display the ping if the host is up, if not it'll say "down".
echo ping("", 80, 10);


I want this for a game server.

The idea is that I can type in the IP address and port number, and I get the ping response.

Answer Source

I think the answer to this question pretty much sums up the problem with your question.

If what you want to do is find out whether a given host will accept TCP connections on port 80, you can do this:

$host = ''; 
$port = 80; 
$waitTimeoutInSeconds = 1; 
if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)){   
   // It worked 
} else {
   // It didn't work 

For anything other than TCP it will be more difficult (although since you specify 80, I guess you are looking for an active HTTP server, so TCP is what you want). TCP is sequenced and acknowledged, so you will implicitly receive a returned packet when a connection is successfully made. Most other transport protocols (commonly UDP, but others as well) do not behave in this manner, and datagrams will not be acknowledged unless the overlayed Application Layer protocol implements it.

The fact that you are asking this question in this manner tells me you have a fundamental gap in your knowledge on Transport Layer protocols. You should read up on ICMP and TCP, as well as the OSI Model.

Also, here's a slightly cleaner version to ping to hosts.

// Function to check response time
function pingDomain($domain){
    $starttime = microtime(true);
    $file      = fsockopen ($domain, 80, $errno, $errstr, 10);
    $stoptime  = microtime(true);
    $status    = 0;

    if (!$file) $status = -1;  // Site is down
    else {
        $status = ($stoptime - $starttime) * 1000;
        $status = floor($status);
    return $status;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download