Here is a script in PHP I wrote to check if a remote host and port are open for you to connect. Do not mistake this as an equivalent to ping command because ping uses ICMP and I used TCP using PHP’s famous fsockopen() function, and a small piece of AJAX.
You can get the latest source code from my GitHub code share page – https://github.com/ninethsense/code-share/
PHP:
function ping($host, $port) {
$startTime = time();
if ($fs = fsockopen($host, $port, $errCode, $errStr, 1)) {
$timeTaken = (time()-$startTime)/1000;
echo "Reply from $host:$port time={$timeTaken}ms";
fclose($fs);
} else {
echo "Request timed out.";
}
echo "<br>";
}
JavaScript:
var count = 0;
var intervalID = setInterval(function PortPing() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("console").innerHTML += this.responseText;
}
};
xhttp.open("GET", "PortPing.php?source=self&host=<?=$host?>&port=<?=$port?>", true);
xhttp.send();
if (++count > <?=$t-1?>) {
clearInterval(intervalID);
}
},2);