0

I wrote a PHP script which simply gets URL for images and tries to download/save them on server.

My problem here is that sometimes the image is not fully loaded and the codes blow only save images partially. I did some research but couldn't figure out if I can add something to it, so it can check whether it is saving the full image or not.

Images sizes and other properties of images are random so I can't check it with those factors unless there is a way that I can get those info before loading them image.

Thank you all.

if ( $leng >= "5" ) {
define('UPLOAD_DIR', dirname(__FILE__) . '/files/');
    $length = 512000;
    $handle = fopen($url, 'rb');
    $filename = UPLOAD_DIR . substr(strrchr($url, '/'), 1);
    $write = fopen($filename, 'w');
    while (!feof($handle))
    {
        $buffer = fread($handle, $length);
        fwrite($write, $buffer);
    }
    fclose($handle);
    fclose($write);

}else {Echo "failed";}

1 Answers1

1

I think that using cURL is a better solution than using fopen for url. Check this out:

$file = fopen($filename, 'wb'); //Write it as a binary file - like image

$c = curl_init($url);
curl_setopt($c, CURLOPT_FILE, $file);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true); //Allow cURL to follow redirects (but take note that this does not work with safemode enabled)
curl_exec($c);
$httpCode = curl_getinfo($c, CURLINFO_HTTP_CODE); //200 means OK, you may check it later, just for sure
curl_close($c);

fclose($file);

Partially based on Downloading a large file using curl

Community
  • 1
  • 1
Luki
  • 214
  • 1
  • 7