Home > Article > Backend Development > How to recursively generate md5 of files in a directory in Linux system, linuxmd5_PHP tutorial
use md5sum under linux to recursively generate md5 of the entire directory
Today I am going to use md5sum to operate a directory and recursively generate the md5 values of all files in the directory. I found that it does not support recursive operations, so I wrote a php script to handle it
Code:
<?php $path ='/data/www/bbs/source'; $outfile = 'file.md5'; get_file_md5($path, $outfile); function get_file_md5($path, $outfile) { $path = rtrim($path, '/'); if(function_exists('scandir')) { $files = scandir($path); foreach($files as $v) { if($v != '.' && $v != '..') { $file = $path.'/'.$v; if(is_dir($file)) { get_file_md5($file, $outfile); }else { file_put_contents($outfile, md5_file($file)." ".$file."\n", FILE_APPEND); } } } }else { $files = opendir($path); while(($f = readdir($files)) !== false) { if($f == '.' || $f == '..') continue; $file = $path.'/'.$f; if(is_dir($file)) { get_file_md5($file, $outfile); }else { file_put_contents($outfile, md5_file($file)." ".$file."\n", FILE_APPEND); } } closedir($files); } }
Note: There are two spaces between the generated md5 value and the file, otherwise the error will be as follows
Copy code The code is as follows: md5sum: file1.md5: no properly formatted MD5 checksum lines found
Let’s do it more simply, use the find command of Linux to get it done in one sentence
Code:
find /data/www/bbs/source -type f -print0 | xargs -0 md5sum > file2.md5
Test
md5sum -c file1.md5 md5sum -c file2.md5
As shown in the picture
This outputs all the test results to the screen. If the last one displays a message like md5sum: WARNING: 2 of 1147 computed checksums did NOT match, it means that 2 of the total 1147 are inconsistent
Then we can
md5sum -c file1.md5 | grep FAILED
It’s easy to know which files have been tampered with