函数文档

verify_file_md5()

💡 云策文档标注

概述

verify_file_md5() 函数用于计算文件的 MD5 哈希值,并与预期值进行比较,以验证文件完整性。它支持 base64 编码或十六进制编码的 MD5 输入,并返回布尔值或 WP_Error 对象。

关键要点

  • 函数接受两个参数:$filename(文件名)和 $expected_md5(预期 MD5 值),后者可以是 32 字符的十六进制字符串或 24 字符的 base64 编码字符串。
  • 返回值:成功时返回 true;MD5 格式未知时返回 false;MD5 不匹配时返回 WP_Error 对象,包含错误消息。
  • 内部使用 md5_file() 计算文件 MD5,并根据 $expected_md5 的长度自动解码为原始二进制格式进行比较。
  • 函数自 WordPress 3.7.0 版本引入,常用于文件下载验证等场景。

代码示例

function verify_file_md5( $filename, $expected_md5 ) {
    if ( 32 === strlen( $expected_md5 ) ) {
        $expected_raw_md5 = pack( 'H*', $expected_md5 );
    } elseif ( 24 === strlen( $expected_md5 ) ) {
        $expected_raw_md5 = base64_decode( $expected_md5 );
    } else {
        return false; // Unknown format.
    }

    $file_md5 = md5_file( $filename, true );

    if ( $file_md5 === $expected_raw_md5 ) {
        return true;
    }

    return new WP_Error(
        'md5_mismatch',
        sprintf(
            /* translators: 1: File checksum, 2: Expected checksum value. */
            __( 'The checksum of the file (%1$s) does not match the expected checksum value (%2$s).' ),
            bin2hex( $file_md5 ),
            bin2hex( $expected_raw_md5 )
        )
    );
}

注意事项

  • 确保 $filename 是有效的文件路径,否则 md5_file() 可能失败。
  • $expected_md5 必须为 32 或 24 字符长度,否则函数返回 false,表示格式未知。
  • 错误处理时,检查返回值是否为 WP_Error 对象,以获取详细的错误信息。

📄 原文内容

Calculates and compares the MD5 of a file to its expected value.

Parameters

$filenamestringrequired
The filename to check the MD5 of.
$expected_md5stringrequired
The expected MD5 of the file, either a base64-encoded raw md5, or a hex-encoded md5.

Return

bool|WP_Error True on success, false when the MD5 format is unknown/unexpected, WP_Error on failure.

Source

function verify_file_md5( $filename, $expected_md5 ) {
	if ( 32 === strlen( $expected_md5 ) ) {
		$expected_raw_md5 = pack( 'H*', $expected_md5 );
	} elseif ( 24 === strlen( $expected_md5 ) ) {
		$expected_raw_md5 = base64_decode( $expected_md5 );
	} else {
		return false; // Unknown format.
	}

	$file_md5 = md5_file( $filename, true );

	if ( $file_md5 === $expected_raw_md5 ) {
		return true;
	}

	return new WP_Error(
		'md5_mismatch',
		sprintf(
			/* translators: 1: File checksum, 2: Expected checksum value. */
			__( 'The checksum of the file (%1$s) does not match the expected checksum value (%2$s).' ),
			bin2hex( $file_md5 ),
			bin2hex( $expected_raw_md5 )
		)
	);
}

Changelog

Version Description
3.7.0 Introduced.