使用PHP和CURL计算下载文件的MD5

I have some cURL call that download a large file. I'm wondering if it is possible to calculate hash when the file is still downloading?

I think the progress callback function is the right place for accomplish that..

function get($urlget, $filename) {

        //Init Stuff[...]                   

        $this->fp = fopen($filename, "w+");
        $ch = curl_init();       


        //[...] irrelevant curlopt stuff

        curl_setopt($ch, CURLOPT_FILE, $this->fp);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_NOPROGRESS, 0);
        curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, array($this,'curl_progress_cb'));

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        $ret = curl_exec($ch);

        if( curl_errno($ch) ){
            $ret = FALSE;
        }

        curl_close($ch);

        fclose($this->fp);        

        return $ret;
    }

    function curl_progress_cb($dltotal, $dlnow, $ultotal, $ulnow ){
        //... Calculate MD5 of file here with $this->fp

    }

Its possible to calculate md5 hash of partially downloaded file, but it does not make too much sense. Every downloaded byte will change your hash diametrally, what is the reason behind going with this kind solution?

If you need to have md5 hash for entire file than the answer is NO. Your program has to first download the file and then generate the hash.

I just do it:

in a file wget-md5.php, add the below code:

<?php
function writeCallback($resource, $data)
{
    global $handle;
    global $handle_md5_val;
    global $handle_md5_ctx;
    $len = fwrite($handle,$data);
    hash_update($handle_md5_ctx,$data);
    return $len;
}
$handle=FALSE;
$handle_md5_val=FALSE;
$handle_md5_ctx=FALSE;
function wget_with_curl_and_md5_hashing($url,$uri) 
{
    global $handle;
    global $handle_md5_val;
    global $handle_md5_ctx;
    $handle_md5_val=FALSE;
    $handle_md5_ctx=hash_init('md5');
    $handle = fopen($uri,'w');
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL,                $url);
    curl_setopt($curl, CURLOPT_BUFFERSIZE,         64000);
    curl_setopt($curl, CURLOPT_WRITEFUNCTION,      'writeCallback');
    echo "wget_with_curl_and_md5_hashing[".$url."]=downloading
";
    curl_exec($curl);
    curl_close($curl);
    fclose($handle);
    $handle_md5_val = hash_final($handle_md5_ctx);
    $handle_md5_ctx=FALSE;
    echo "wget_with_curl_and_md5_hashing[".$url."]=downloaded,md5=".$handle_md5_val."
";
}
wget_with_curl_and_md5_hashing("http://archlinux.polymorf.fr/core/os/x86_64/core.files.tar.gz","core.files.tar.gz");
?>

and run:

$ php -f wget-md5.php
wget_with_curl_and_md5_hashing[http://archlinux.polymorf.fr/core/os/x86_64/core.files.tar.gz]=downloading
wget_with_curl_and_md5_hashing[http://archlinux.polymorf.fr/core/os/x86_64/core.files.tar.gz]=downloaded,md5=5bc1ac3bc8961cfbe78077e1ebcf7cbe

$ md5sum core.files.tar.gz 
5bc1ac3bc8961cfbe78077e1ebcf7cbe  core.files.tar.gz