md5_file() 直接計算檔案的 MD5 雜湊值,適用於上傳檔案去重、完整性驗證、快取失效判斷等場景,避免將大檔案讀入記憶體再計算。
// 上傳處理中取得暫存檔 MD5
if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
$md5 = md5_file($_FILES['file']['tmp_name']);
echo "檔案 MD5:{$md5}";
}
$file = 'data.zip'; $hash = md5_file($file); file_put_contents($file . '.md5', $hash);
$file = 'data.zip';
$saved = file_get_contents($file . '.md5');
if (md5_file($file) === $saved) {
echo "檔案完整,未被修改";
} else {
echo "警告:檔案內容已變更!";
}
md5_file(string $filename, bool $binary = false): string|false$binary = true 回傳 16 字元原始二進位;false(預設)回傳 32 字元十六進位字串false(檔案不存在、權限不足等)$hash = hash_file('sha256', $file); // 需 PHP 5.1.2+
// 或
$ctx = hash_init('sha256');
hash_update_stream($ctx, fopen($file, 'rb'));
$hash = hash_final($ctx);