tags:

views:

198

answers:

2

Hi everyone

I have a script where I have to download some files and to make sure that everything worked fine I'm comparing MD5 checksums.

I have found that the checksums are not correct when downloading with CURL. The script below demonstrates this. It downloads the Google logo and compares checksums.

$url = 'http://www.google.com/intl/en_ALL/images/logo.gif';

echo md5_file($url)."\n";

$path = 'f1';
file_put_contents($path, file_get_contents($url));
echo md5_file($path)."\n";


$path = 'f2';
$out = fopen($path, 'wb');
$ch = curl_init();
curl_setopt($ch, CURLOPT_FILE, $out);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
curl_close($ch);
echo md5_file($path)."\n";

the output is:

e80d1c59a673f560785784fb1ac10959
e80d1c59a673f560785784fb1ac10959
d83892759d58a1281e3f3bc7503159b5

The first two are correct (they match the MD5 checksum when I download the logo using firefox) and the result produced by curl is not OK.

any ideas how to fix that?

thanks for your help

UPDATE:

interestingly the code below works just fine and produces the correct output. The problem really only seems to exist when saving to a file. Unfortunately I have to save directly to a file since the files I'm downloading can get rather large.

$path = 'f3';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
file_put_contents($path, curl_exec ($ch));
echo md5_file($path)."\n";
curl_close ($ch);
+1  A: 

You're missing an fclose($out), which could account for md5_file seeing an incomplete file.

Victor Nicollet
thanks for your answer - unfortunately that's not it. I tried putting in fclose($out) but it didn't work
MarcS
While playing around I accidentally pasted fclose($out); fclose($out); in the code. For whatever reason closing it twice makes it work. I have absolutely no idea why this is the case.
MarcS
+1  A: 

Try to add

curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);

To your curl options

Eineki