0

I am creating custom functionality to import list of images on my server from their url. The issue is some images are copied and some images file size is 0B. If i open that image url in browser it shows me correct image.

I am using copy function to copy image:

 copy($img, DIR_IMAGE.'catalog/'.$filename);

Where $img contains http url of image and $filename contain basename of image.

I also tried another alternate:

            $file = fopen ($img, "rb");
            if ($file)
            {
                $newf = fopen (DIR_IMAGE.'catalog/'.$filename, "wb");

                if ($newf)
                while(!feof($file)) 
                {
                    fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
                }
            }
            if ($file) 
            {
                fclose($file);
            }

            if ($newf) 
            {
                fclose($newf);
            }

Can anyone suggest me how to fix this issue.

Thanks in Advance.

B001ᛦ
  • 2,036
  • 6
  • 23
  • 31
dev tester
  • 327
  • 1
  • 10
  • 25

1 Answers1

0

It may be image hotlink protection, if it's the case you'll have to make a slightly more complex call to download that picture:

$ch = curl_init();
$fp = fopen(DIR_IMAGE.'catalog/'.$filename, "w");
curl_setopt($ch, CURLOPT_URL, $img);
curl_setopt($ch, CURLOPT_MUTE, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/c");
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/c");
curl_setopt($ch, CURLOPT_REFERER, "http://".$imgDomain."/");
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0");
curl_exec($ch);
curl_close($ch);
fclose($fp);

You'll also need to know the domain on with the image can be accessed (which can or not be the same it's hosted) and supply it as a referer header (as above).

emiliopedrollo
  • 910
  • 6
  • 21
  • $imgDomain is the domain name from where i am copying image – dev tester Feb 09 '17 at 12:20
  • Yes, it should be. The referer is suppose to be the address from within the request was made (somewhere with permissions to see the picture) – emiliopedrollo Feb 09 '17 at 12:44
  • I tried above solution but still it's not copying some images.. :( – dev tester Feb 10 '17 at 10:13
  • Then probably it isn't hotlink protection, can you provide some working examples and some who doesn't – emiliopedrollo Feb 10 '17 at 13:24
  • Here is the working one [link](http://www.surrounding.com.asp1-10.ord1-1.websitetestlink.com/uploads/Products/LucePlan/asset_upload_file81_965.jpg) and here is one which is not working [link](http://www.surrounding.com.asp1-10.ord1-1.websitetestlink.com/uploads/Products/LucePlan/asset_upload_file34_965.jpg) – dev tester Feb 14 '17 at 06:08