Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php file_get_contents() get stuck in loading an image

As mentioned above, the php file_get_contents() function or even the fopen()/fread() combination stucks and times out when trying to read this simple image url:

http://pics.redblue.de/artikelid/GR/1140436/fee_786_587_png

but the same image is easily loaded by browsers, whats the catch?

EDITED:

as requested in comments, I am showing the function I used to get the data:

function customRead($url)
{
    $contents = '';

    $handle = fopen($url, "rb");

    $dex = 0;

    while ( !feof($handle) )
    {
        if ( $dex++ > 100 )
            break;

        $contents .= fread($handle, 2048);
    }

    fclose($handle);

    echo "\nbreaking due to too many calls...\n";

    return $contents;
}

I also tried simply this:

echo file_get_contents('http://pics.redblue.de/artikelid/GR/1140436/fee_786_587_png');

Both give the same issue

EDITED:

As suggested in comment I used curl:

$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11');
    $res = curl_exec($ch);
    $rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
    curl_close($ch) ;
    echo "\n\n\n[DATA:";
    echo $res;
    echo "]\n\n\n[CODE:";
    print_r($rescode);
    echo "]\n\n\n[ERROR:";
    echo curl_error($ch);
    echo "]\n\n\n";

this is the result:

[DATA:]

[CODE:0]

[ERROR:]
like image 492
Imran Ahmed Avatar asked Nov 08 '22 20:11

Imran Ahmed


1 Answers

If you don't get the remote data with file_get_contents, you can try it with cURL as it can provide error messages on curl_error. If you get nothing, even no error, then something on your server blocks outgoing connections. Maybe you even want to try curl over SSH. I'm not sure if that makes any difference but it's worth the try. If you don't get anything you may want to consider contacting the server admin (if you're not that) or the provider.

like image 100
Charlotte Dunois Avatar answered Nov 14 '22 23:11

Charlotte Dunois