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

问题描述 投票:3回答:2

我有一些下载大文件的cURL调用。我想知道是否有可能在文件仍在下载时计算哈希值?

我认为进度回调函数是完成它的正确位置..

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

    }
php curl md5
2个回答
0
投票

它可以计算部分下载文件的md5哈希值,但它没有多大意义。每个下载的字节都会直接改变你的哈希值,这种解决方案背后的原因是什么?

如果你需要为整个文件使用md5哈希,那么答案是否定的。您的程序必须先下载该文件,然后生成哈希。


-1
投票

我只是这样做:

在文件wget-md5.php中,添加以下代码:

<?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\n";
    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."\n";
}
wget_with_curl_and_md5_hashing("http://archlinux.polymorf.fr/core/os/x86_64/core.files.tar.gz","core.files.tar.gz");
?>

并运行:

$ 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
© www.soinside.com 2019 - 2024. All rights reserved.