verify_file_md5

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

Description

(bool|object) verify_file_md5( (string) $filename, (string) $expected_md5 ); 

Returns (bool|object)

WP_Error on failure, true on success, false when the MD5 format is unknown/unexpected

Parameters (2)

0. $filename (string)
The filename to check the MD5 of.
1. $expected_md5 (string)
The expected MD5 of the file, either a base64 encoded raw md5, or a hex-encoded md5

Usage

  1. if ( !function_exists( 'verify_file_md5' ) ) { 
  2. require_once ABSPATH . '/wp-admin/includes/file.php'; 
  3.  
  4. // The filename to check the MD5 of. 
  5. $filename = ''; 
  6.  
  7. // The expected MD5 of the file, either a base64 encoded raw md5, or a hex-encoded md5 
  8. $expected_md5 = ''; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = verify_file_md5($filename, $expected_md5); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-admin/includes/file.php  
  1. function verify_file_md5( $filename, $expected_md5 ) { 
  2. if ( 32 == strlen( $expected_md5 ) ) 
  3. $expected_raw_md5 = pack( 'H*', $expected_md5 ); 
  4. elseif ( 24 == strlen( $expected_md5 ) ) 
  5. $expected_raw_md5 = base64_decode( $expected_md5 ); 
  6. else 
  7. return false; // unknown format 
  8.  
  9. $file_md5 = md5_file( $filename, true ); 
  10.  
  11. if ( $file_md5 === $expected_raw_md5 ) 
  12. return true; 
  13.  
  14. return new WP_Error( 'md5_mismatch', sprintf( __( 'The checksum of the file (%1$s) does not match the expected checksum value (%2$s).' ), bin2hex( $file_md5 ), bin2hex( $expected_raw_md5 ) ) );