CJD CJD - 5 months ago 28
PHP Question

file_get_contents() connection refused for my own site

I've been trying to connect to my own site using both CURL and the PHP file_get_contents() function to get source of my webpage without success. I am running the PHP script on the same server that I am trying to get the HTML source from. CURL doesn't return any errors, not even when using curl_error(), and the PHP file_get_contents() function returns the following:

Warning: file_get_contents([sitename]) [function.file-get-contents]: failed to open stream: Connection refused in [file path] on line 19.

I've no idea why this is. Why would a server actively refuse this connection? How can I stop it?



For reference here is my (cURL) code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.mydomain.co.uk');
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, '');
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv: Gecko/20090729 Firefox/3.5.2');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: www.mydomain.co.uk'));

$rawHTML = curl_exec($ch);
$err = curl_error($ch);

print $err;
print 'HTML: ' . $rawHTML;


Have a look at your firewall settings, they may be a little too strict. What happens if you log in and

telnet localhost 80

or the equivalent for your os of choice? And try the same not with localhost but the full ip of your server. Only if it succeeds, you have a curl/php problem.

edit: ok, so connection to localhost works, using file_get_contents("http://localhost/");.

This means that you can access you site through localhost, but you need to override the Host: field sent with the request. This is not exactly normal usage of cURL, but you may try:

curl_setopt(CURLOPT_HTTPHEADER,array('Host: yourdomain.com'));

while requesting URL I wonder if this will be understood by curl but you can give it a shot.

edit^2: If this does not work to trick cURL, just open your own socket connection and make your own request:

$ip = '';
$fp = fsockopen($ip, 80, $errno, $errstr, 5);
$result = '';
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: www.exampl.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        $result .= fgets($fp, 128);

(this is an adaption from a php.net example)