书接上文,如何利用PHP批量生成目录下每个文件的md5值并写入到结果文件中?

这里引用了转自简书 作者 Renew_ 发布的方法:

话不多说直接上代码:

<?php

/**
 * @author Renew。
 * @date 2019-12-15
 *
 */
class FileMD5
{
    /**
     * 要批量md5加密的文件目录
     * @var string
     */
    public static $appFolder = "";

    /**
     * 生成md5的文件名
     * @var string
     */
    public static $generateMd5FilePath = "";

    /**
     * 开始
     * @throws Exception
     */
    public static function start()
    {
        $manifestHandle = fopen(FileMD5::$generateMd5FilePath, "w+");

        FileMD5::traverse(FileMD5::$appFolder, $manifestHandle);

        fclose($manifestHandle);
    }

    /**
     * 遍历应用根目录下的文件,并生成对应的文件长度及md5信息
     * @param $appPath
     *  应用根目录,如:xxx/xxx/analytics
     * @param $manifestHandle
     * 生成的manifest文件存放位置的文件句柄
     * @throws Exception
     */
    public static function traverse($appPath, $manifestHandle)
    {
        if (!file_exists($appPath)) throw new Exception($appPath . " does not exist!");

        if (!is_dir($appPath)) throw new Exception($appPath . " is not a directory!");

        if (!($dh = opendir($appPath))) throw new Exception($appPath . " Failure while read diectory!");

        while (($file = readdir($dh)) != false) {
            $subDir = $appPath . DIRECTORY_SEPARATOR . $file;

            if ($file == "." || $file == "..") {
                continue;
            } else if (is_dir($subDir)) {
                FileMD5::traverse($subDir, $manifestHandle);
            } else {
                FileMD5::writeOneFieToManifest($subDir, $manifestHandle);
            }
        }

        closedir($dh);
    }

    /**
     * 写一个文件的md5信息到文件中
     * @param $filePath
     * @param $fileHandle
     * @throws Exception
     */
    public static function writeOneFieToManifest($filePath, $fileHandle)
    {
        if (!file_exists($filePath)) throw new Exception($filePath . ' file not exist!');

        $relativePath = str_replace(FileMD5::$appFolder . DIRECTORY_SEPARATOR, '', $filePath);

        $relativePath = str_replace("\\", "/", $relativePath);

        $fileMd5 = @md5_file($filePath);

        $content = $relativePath . ' => ' . $fileMd5 . "\n";

        if (!fwrite($fileHandle, $content)) throw new Exception($filePath . ' can not be written!');
    }

}

try {

    if (isset($argv[1])) FileMD5::$appFolder = $argv[1];

    if (isset($argv[2])) FileMD5::$generateMd5FilePath = $argv[2];

    FileMD5::start();
} catch (Exception $e) {
    exit($e->getMessage());
}

2.执行命令

php md5.php "/var/www/" "/var/www/md5.txt"

这样就将www目录下内容的MD5值生成存储到md5.txt之中了。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。