Reputation: 7404
I am using the following API for getting the country code using IP
http://api.hostip.info/country.php?ip=' . $IP
Example: on Localhost
$IP = '202.71.158.30';
//pass the ip as a parameter for follow URL it will return the country
$country_code = file_get_contents('http://api.hostip.info/country.php?ip=' . $IP);
and its working fine here and showing the country code.
But it showing error on Server
Example:
$IP=$_SERVER['REMOTE_ADDR'];
$country_code = file_get_contents('http://api.hostip.info/country.php?ip=' . $IP);
Showing following error:
Warning: file_get_contents(http://api.hostip.info/country.php?ip=101.63.xx.xxx) [function.file-get-contents]: failed to open stream: Connection refused in /srv/disk4/1322145/www/servername.in/app/header.php on line 12
Whats wrong with this?
Upvotes: 14
Views: 64238
Reputation: 76
add optional parameter in file_get_contents using stream_context_create function to open stream connection valid.
$context = stream_context_create([
'http' => ['protocol_version' => '1.1'],
]);
$result = file_get_contents($url, false, $context);
var_dump($result);
Upvotes: 1
Reputation: 924
Use curl method instead of file_get_contents()
It does not work on localhost at google.com. Instead use other engine or use curl below:
Make a function or use inside the same function:
I prefer it to use in a function to avoid repetition in future.
$IP = '202.71.158.30';
$country_code = file_get_contents_fun('http://api.hostip.info/country.php?
ip='.$IP);
public function file_get_contents_fun($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT,30);
$content = curl_exec ($ch);
curl_close ($ch);
return $content;
}
Upvotes: 4
Reputation: 3127
In my case the Fail2Ban
extension in Plesk suddenly started IP-blocking the server that did the file_get_contents()
requests. This is probably not going to be the issue, but I just wanted you to be aware of such a possibility.
Upvotes: 3
Reputation: 677
You can use CURL in place of file_get_contents()
<?php
$IP = '202.71.158.30';
$runfile = 'http://api.hostip.info/country.php?ip=' . $IP;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $runfile);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec ($ch);
curl_close ($ch);
echo $content;
Upvotes: 14
Reputation: 4111
Some servers do not permit accessing through IP address in your request.
You can use CURL
to prevent this problem.
Upvotes: 3