Created
December 19, 2020 16:56
-
-
Save trafficinc/a603f8c7c139dcb8ddefc71a29e1a253 to your computer and use it in GitHub Desktop.
Ping Website on Mac/Linux 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 | |
class Ping { | |
private $host; | |
private $ttl; | |
private $timeout; | |
public $commandOut; | |
private $localhost = false; | |
public function __construct($host, $ttl = 255, $timeout = 10) { | |
if (!isset($host)) { | |
throw new \Exception("Error: Host name not supplied."); | |
} | |
$this->host = $host; | |
$this->ttl = $ttl; | |
$this->timeout = $timeout; | |
} | |
public function pingDomain(){ | |
$latency = false; | |
$ttl = escapeshellcmd($this->ttl); | |
$timeout = escapeshellcmd($this->timeout); | |
$host = escapeshellcmd($this->host); | |
// for Mac OS | |
if (strtoupper(PHP_OS) === 'DARWIN') { | |
$exec_string = 'ping -n -c 1 -m ' . $ttl . ' -t ' . $timeout . ' ' . $host; | |
} else { | |
// for UNIX-based OS | |
$exec_string = 'ping -n -c 1 -t ' . $ttl . ' -W ' . $timeout . ' ' . $host . ' 2>&1'; | |
} | |
exec($exec_string, $output, $return); | |
$this->commandOut = implode('', $output); | |
$output = array_values(array_filter($output)); | |
if (!empty($output[1])) { | |
// Search for a 'time' value in the result line. | |
$response = preg_match("/time(?:=|<)(?<time>[\.0-9]+)(?:|\s)ms/", $output[1], $matches); | |
// If there's a result and it's greater than 0, return the latency. | |
if ($response > 0 && isset($matches['time'])) { | |
$latency = round($matches['time'], 4); | |
} | |
} | |
return $latency ." ms\n"; | |
} | |
public function getCommandOut() { | |
return $this->commandOut; | |
} | |
} | |
// Implementation, $ php PHPping.php | |
$ping = new Ping('www.youtsite.com',225,10); | |
echo $ping->pingDomain(); | |
echo $ping->getCommandOut(); // to see actual ping | |
// result: 15.03 ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment