Determining Internet Connectivity in PHP Scripts
When a script needs to verify external availability before attempting operations like downloads, relying on wget output alone is often insufficient. In your specific scenario, if wget fails to resolve a host or cannot reach the server, it might simply exit with an error code that you can catch. However, distinguishing between "file not found" (404) and "network unreachable" requires explicit connectivity checks before the download command even runs.
The most reliable approach in PHP is to leverage built-in functions that test DNS resolution or actual TCP handshake capability. These methods are independent of any specific web server configuration on your target, making them robust for development machines where local routing rules might differ from production environments.
Checking DNS Resolution First
Before attempting a raw socket connection, verifying that the domain name resolves to an IP address is a quick sanity check. PHP provides gethostbyname() or dns_get_record() for this purpose. If these functions return false or throw a warning, your machine cannot resolve the hostname, indicating a broken DNS configuration or no internet access at all.
$domain = 'example.com';
$resolved = @gethostbyname($domain);
if ($resolved === false) {
echo "DNS resolution failed for $domain.";
exit;
}
echo "$domain resolved to: $resolved";
The error suppression operator (@) here is crucial. DNS lookups can sometimes trigger warnings if the system's php.ini settings regarding logging are aggressive, or if the underlying C library reports issues unrelated to your logic. Suppressing these allows you to focus strictly on the boolean result of the resolution itself. If this step passes, you know the nameserver is reachable and the hostname exists in the public DNS space.
Verifying TCP Connectivity with fsockopen
Resolving a domain name does not guarantee an active internet connection; it only confirms that the name can be translated. To confirm actual network reachability, you need to attempt a low-level socket connection. The standard function for this is fsockopen().
You should aim to connect to a reliable, public endpoint rather than your specific download target. This prevents false negatives caused by the target server being down or blocking access during your test. A common practice is to ping a well-known CDN node or a simple HTTP service like httpbin.org on port 80 or 443.
$host = 'example.com';
$port = 80; // Or 443 for HTTPS checks
$timeout = 5;
$connection = @fsockopen($host, $port, $errno, $errstr, $timeout);
if (!$connection) {
echo "Network connectivity check failed.";
// Log $errno and $errstr for debugging
exit;
} else {
fclose($connection);
echo "Internet connection confirmed. Proceeding with wget.";
}
This code attempts to open a socket to the specified host and port. If the script times out or encounters a network unreachable error, $connection will be false. The timeout parameter is essential; without it, a blocked or unresponsive server could hang your entire PHP process indefinitely.
Integrating with wget Logic
Once you have confirmed connectivity via DNS resolution and a successful socket handshake, you can safely proceed with your file download logic. Your original workflow likely looked something like this:
wget https://example.com/file1.zip
wget https://example.com/file2.zip
By wrapping the wget calls in a conditional block that only executes if the connectivity check passed, you ensure that "file not found" errors are distinct from network outages. If the connectivity check fails, you can abort the batch download immediately, saving time and preventing confusing exit codes from individual wget runs.
Trade-offs and Considerations
While checking against a random domain works for general connectivity tests, it does not account for firewall rules or specific routing requirements that might apply to your actual download targets. If your script is designed to download files only when the internet is up, but you are behind a proxy that requires authentication, a simple fsockopen might fail if headers aren't configured correctly in PHP's context.
In production environments, relying solely on IP addresses or public APIs for health checks can introduce latency or dependency on third-party services. For development machines, however, this approach offers the best balance of simplicity and accuracy without requiring external infrastructure like a dedicated load balancer or health endpoint. Always remember that fsockopen connects to TCP port 80 by default when no port is specified; ensure you specify the correct port if your test target uses HTTPS (port 443).