php 遍历目录,生成目录下每个文件的md5值并写入到结果文件中

+ -
0
php 遍历目录,生成目录下每个文件的md5值并写入到结果文件中

php 遍历目录,生成目录下每个文件的md5值并写入到结果文件中

1.不多说,复制代码
<?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"


转自简书 作者 Renew_
信息
想要留言? 请 登录 您的账号。还没有? 你可以 免费创建账号

Comments 0