Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP- file_get_contents failed to open stream: Connection refused

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?

like image 623
J.K.A. Avatar asked Apr 05 '13 13:04

J.K.A.


3 Answers

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;
like image 187
Pankaj Dadure Avatar answered Nov 17 '22 15:11

Pankaj Dadure


Some servers do not permit accessing through IP address in your request. You can use CURL to prevent this problem.

like image 37
Amir Avatar answered Nov 17 '22 14:11

Amir


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.

like image 33
Floris Avatar answered Nov 17 '22 13:11

Floris