Created
July 16, 2025 15:22
-
-
Save hctilg/a42492c873b2eb50a1f7643103743eca to your computer and use it in GitHub Desktop.
How can I ping a server port with PHP?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function ping($ip, $port = 80, $timeout = 1) { | |
try { | |
$output = []; | |
$result = null; | |
exec("ping -c 4 " . escapeshellarg($ip), $output, $result); | |
if ($result === 0) { | |
foreach ($output as $line) { | |
if (preg_match('/time=(\d+\.\d+) ms/', $line, $matches)) { | |
return floatval($matches[1]) . 'ms'; | |
} | |
} | |
} | |
} catch (\Throwable $th) { | |
$start = microtime(true); | |
$fp = @fsockopen($ip, $port, $errno, $errstr, $timeout); | |
if ($fp) { | |
fclose($fp); | |
$end = microtime(true); | |
$duration = ($end - $start) * 1000; // to millisecond | |
return round($duration, 2) . 'ms'; | |
} | |
} | |
return 'Unavailable'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment