Skip to content

Instantly share code, notes, and snippets.

@hctilg
Created July 16, 2025 15:22
Show Gist options
  • Save hctilg/a42492c873b2eb50a1f7643103743eca to your computer and use it in GitHub Desktop.
Save hctilg/a42492c873b2eb50a1f7643103743eca to your computer and use it in GitHub Desktop.
How can I ping a server port with PHP?
<?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