The image can not be downloaded using file_get_contents


I am using the below mentioned code to download image.


$doc_root= $_SERVER['DOCUMENT_ROOT'];
$image_upload_path = $doc_root . '/';
$image_name2 = 'img-' . time() . '.jpg';

$destination  = $image_upload_path . $image_name2;

$data = file_get_contents($image_url);
$file = fopen($destination, "w+");
fputs($file, $data);

The above mentioned code is working fine in development environment to download image from any website. The code also works in live site to download images from other website except only one site.

The image seems to be downloaded but whenever i am trying to open the image using any image viewer, an error message is being displayed which is given below.

Could not load image 'img-65456465.jpg'. Error interpreting JPEG image file (Not a JPEG file: starts with 0x3c 0x21)

I checked the error log as well but found no issue. I am not understanding why its image download functionality is not working with that particular website only.

Note: 1) I checked that the original image type hosted in that website is JPEG only.

EDIT: When i am trying to view the downloaded image using browser, i found the below mentioned error.

The image '' can not be displayed because it contains error.

As per suggestion, i am providing the original website link. Website: Image: any image link from this website. For example

Any help on this will be appreciated.

What if you change the fopen() to:

$file = fopen($destination, "wb+"); // binary writing

Let me know.


Here's the code that will work:

ini_set('display_errors', 1);
ini_set('log_errors', 0);

$opts = array(
    'header'=>"Accept-language: en\r\n" .
        "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:23.0) Gecko/20100101 Firefox/23.0\r\n" .

$image_url = '';

$doc_root= $_SERVER['DOCUMENT_ROOT'];
$image_upload_path = $doc_root . '/';
$image_name2 = 'img-' . time() . '.jpg';

$destination  = $image_upload_path . $image_name2;

$data = file_get_contents($image_url, false, stream_context_create($opts));
//$file = fopen($destination, "w+");
//fputs($file, $data);
header("Content-type: image/jpeg");
echo $data;

stream_context_create() with the referrer to the original site did the trick.