PHP- file_get_contents failed to open stream: Connection refused
You are encountering a classic symptom of network environment discrepancies: file_get_contents() works perfectly on your local machine but throws a "Connection refused" error on your production server. The fact that the same HTTP endpoint (http://api.hostip.info/country.php) returns data locally while failing remotely suggests the issue isn't with the API itself, nor is it necessarily a firewall blocking outbound traffic entirely. It is almost certainly a configuration mismatch regarding how the PHP runtime handles network streams on the server.
The most common culprit in this scenario is the allow_url_fopen directive. When running code from your desktop or a local XAMPP/WAMP installation, you might be testing with default settings where URL fetching via file functions is enabled by default. However, many production PHP environments, particularly those using FPM (FastCGI Process Manager), disable this feature for security reasons to prevent arbitrary script execution against remote resources unless explicitly needed. If allow_url_fopen is set to Off, the underlying C library responsible for opening URLs via file_get_contents() will reject the request immediately, resulting in the specific error you are seeing.
To verify this hypothesis, you need to inspect the server's configuration. You can do this by creating a temporary PHP file at the root of your web directory or using the command line:
php -i | grep allow_url_fopen
If the output shows allow_url_fopen => Off, that is your problem. The solution involves enabling this directive in your php.ini file or creating a dedicated configuration file (like 99-local.ini) and ensuring it is loaded by your PHP-FPM pool or Apache module. Alternatively, you can modify the .user.ini file in your project directory if your server supports it.
However, relying on allow_url_fopen is not always the best architectural decision. While enabling it resolves the immediate error, it exposes your application to potential security risks by allowing remote code execution via URLs. A more robust and secure approach is to bypass file_get_contents() entirely and utilize cURL, which offers finer-grained control over SSL verification, timeouts, and headers without requiring global configuration changes.
Here is how you can refactor the logic using cURL:
$ip = $_SERVER['REMOTE_ADDR'];
$url = 'http://api.hostip.info/country.php?ip=' . $ip;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Optional: Set timeout to prevent hanging requests
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Use true in production with valid certs
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode === 200) {
$country_code = trim($response);
} else {
// Handle error or fallback logic
$country_code = null;
}
curl_close($ch);
Switching to cURL isolates the network logic within the script rather than relying on global PHP directives. It also allows you to gracefully handle HTTP errors and timeouts, which is crucial when dealing with external third-party APIs that might be slow or down. While file_get_contents is convenient for simple tasks, cURL provides a more predictable behavior in production environments where resource management and error handling are paramount.