本页二维码,扫一扫分享到朋友圈
朋友圈

php文件hash算法,秒传原理


阅读151 评论0 赞 27返回首页    go 编程与技术  go php


header(‘Content-type:text/html;Charset=UTF-8‘);

define(‘blockSize‘, 4*1024*1024);

var_dump(fileHash(‘test.wmv‘));

var_dump(fileHash(‘asdf.wmv‘));

function fileHash($file)

{

$f = fopen($file, "r");

if (!$f) exit("open $file error");

$fileSize = filesize($file);

$buffer = ‘‘;

$sha = ‘‘;

// 一共有多少分片

$blkcnt = $fileSize/blockSize;

if ($fileSize % blockSize) $blkcnt += 1;

// 把数据装入一个二进制字符串

$buffer .= pack("L", $blkcnt);

if ($fileSize <= blockSize) {

$content = fread($f, blockSize);

if (!$content) {

fclose($f);

exit("read file error");

}

$sha .= sha1($content, TRUE);

} else {

for($i=0; $i<$blkcnt; $i+=1) {

$content = fread($f, blockSize);

if (!$content) {

if (feof($f)) break;

fclose($f);

exit("read file error");

}

$sha .= sha1($content, TRUE);

}

$sha = sha1($sha, TRUE);

}

$buffer .= $sha;

$hash = urlSafeEncode(base64_encode($buffer));

fclose($f);

return array($hash, null);

}

function urlSafeEncode($data)

{

$find = array(‘+‘, ‘/‘);

$replace = array(‘-‘, ‘_‘);

return str_replace($find, $replace, $data);

}


  上一篇:go PHP使用sphinx全文检索教程
  下一篇:go php获取字符串中各个字符出现的次数


评论


用QQ登录管理/创建网站 用微博登录管理/创建网站   发布于:04-21