How can error handling be improved in the provided PHP script for checking server ports?
The issue with the provided PHP script for checking server ports is that it lacks proper error handling, which can lead to unexpected behavior or crashes if a port check fails. To improve error handling, we can use try-catch blocks to catch and handle any exceptions that may occur during the port checking process.
<?php
$ports = [80, 443, 3306]; // Ports to check
foreach ($ports as $port) {
$host = 'localhost';
$connection = @fsockopen($host, $port, $errno, $errstr, 3); // Attempt to open a socket connection to the port
try {
if (!$connection) {
throw new Exception("Failed to connect to port {$port}: {$errstr}");
} else {
echo "Port {$port} is open\n";
}
} catch (Exception $e) {
echo $e->getMessage() . "\n";
}
if ($connection) {
fclose($connection); // Close the socket connection
}
}
?>