spatie/ping
Run ICMP ping from PHP and get structured results. Spatie Ping wraps the system ping command, parsing packet loss, transmit/receive counts, min/max/avg times, standard deviation, per-line responses, and error status for quick connectivity checks.
Installation:
composer require spatie/ping
No additional configuration is required—just autoload.
First Ping:
use Spatie\Ping\Ping;
$result = Ping::to('google.com')->ping();
Outputs a structured result with:
success (bool)latency (ms)packetLoss (int)error (string|null)Key Files:
vendor/spatie/ping/src/Ping.php (core class)vendor/spatie/ping/tests/ (test cases for edge cases)$ping = Ping::to('example.com');
if ($ping->ping()->success) {
// Log success or trigger notification
}
Batch Pinging:
$hosts = ['google.com', 'github.com', 'spatie.be'];
$results = collect($hosts)->map(fn($host) => Ping::to($host)->ping());
Useful for monitoring multiple endpoints.
Retry Logic:
$attempts = 3;
$result = null;
while ($attempts--) {
$result = Ping::to('flaky-service.com')->ping();
if ($result->success) break;
}
Latency Thresholds:
$ping = Ping::to('api.example.com')->ping();
if ($ping->latency > 500) {
// Alert on high latency
}
Queue Jobs:
Ping::to('critical-service.com')->ping()->then(function ($result) {
if (!$result->success) {
dispatch(new NotifyAdmins($result->error));
}
});
Use Laravel’s queue system to avoid blocking requests.
Caching Results:
$cacheKey = 'ping:google.com';
$result = Cache::remember($cacheKey, now()->addMinutes(5), function () {
return Ping::to('google.com')->ping();
});
Logging:
Ping::to('db.example.com')->ping()->then(function ($result) {
Log::info('Ping result', ['host' => 'db.example.com', 'success' => $result->success]);
});
Firewall/Network Restrictions:
$response = Http::get('https://example.com/health')->throw();
Timeout Handling:
Ping::to('slow-host.com')->timeout(5); // 5 seconds
DNS Resolution:
Ping::to('8.8.8.8')->ping(); // Skip DNS lookup
Packet Loss Interpretation:
packetLoss is a percentage. A value of 0 means no loss, but null may indicate an error (e.g., unreachable host).Verbose Output:
Enable debug mode to see raw ICMP output (not officially supported, but you can inspect the underlying exec calls via Ping::to('host')->debug()).
Common Errors:
"Command not found": Ensure ping is installed on the server (Linux/macOS: ping, Windows: ping.exe)."Permission denied": Run Laravel’s queue worker with sufficient privileges.Custom Ping Commands:
Override the default ping command for specific use cases (e.g., TCP port checks):
use Spatie\Ping\Ping;
class CustomPing extends Ping {
protected function getCommand(): string {
return 'ping -c 1 -W 2 ' . $this->host;
}
}
Event Dispatching: Trigger events on ping results:
Ping::to('monitor.com')->ping()->then(function ($result) {
event(new PingResult($result));
});
Testing:
Mock Ping in tests:
Ping::shouldReceive('ping')->andReturn((object) ['success' => true, 'latency' => 100]);
How can I help you explore Laravel packages today?