Current Location: Home> Latest Articles> How to record the md5_file() value of all files into the log

How to record the md5_file() value of all files into the log

M66 2025-05-31

In PHP, the md5_file() function is a very convenient tool. It can directly calculate the MD5 hash value of a specified file, which is often used for file integrity verification. This article will introduce how to use the md5_file() function to iterate through all files in a directory and record their MD5 hash values ​​into a log file.


1. Introduction to md5_file() function

md5_file(string $filename): string|false

  • Parameter $filename : The file path to calculate MD5.

  • Return value: MD5 hash string of the file, if failed, return false .

Example:

 $hash = md5_file('path/to/file.txt');
echo $hash;

2. Implementation ideas

  1. Use PHP's recursive directory traversal function (such as RecursiveDirectoryIterator ) to get all file paths.

  2. Call the md5_file() function for each file to get the hash value.

  3. Write the file path and the corresponding MD5 value to the log file.


3. Code example

 <?php
// The directory path to traverse
$directory = '/path/to/your/directory';

// Log file path
$logFile = '/path/to/your/logfile.log';

// Open the log file,Append write
$logHandle = fopen($logFile, 'a');
if (!$logHandle) {
    die("无法Open the log file\n");
}

// Recursively traverse directory
$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS)
);

foreach ($iterator as $file) {
    if ($file->isFile()) {
        $filePath = $file->getPathname();
        // Calculate the fileMD5Hash value
        $hash = md5_file($filePath);
        if ($hash !== false) {
            // Write to log format:File path + MD5value
            $logLine = $filePath . ' : ' . $hash . PHP_EOL;
            fwrite($logHandle, $logLine);
        } else {
            // Record error information
            $logLine = $filePath . " : Unable to calculateMD5value" . PHP_EOL;
            fwrite($logHandle, $logLine);
        }
    }
}

fclose($logHandle);

echo "All filesMD5value已记录到日志中。\n";
?>

4. Description

  • Make sure that the PHP script has read and write permissions to the specified directory and log files.

  • To avoid excessive log files, you can clean them regularly or split the log files by date.

  • If you want to output the file path that contains a URL, you can replace the domain name part, for example, replace https://example.com/path/file.jpg with https://m66.net/path/file.jpg .

For example: