不灭的焱

革命尚未成功,同志仍须努力

作者:php-note.com  发布于:2020-02-11 23:19  分类:PHP基础  编辑

PHP 分割、合并 大文件

<?php
/**
 * 分割文件
 * 默认大小 2M=10485760/5
 *
 * @param string 文件名
 * @param float|int $block_size 分块大小
 * @return array
 */
function file_split($file_path = '', $block_size = 10485760 / 5) {
    if (empty($file_path)) {
        return [];
    }

    $block_info = [];
    $size       = filesize($file_path);
    $ext        = file_ext($file_path);
    $file_name  = str_replace($ext, '', $file_path);
    $i          = 0;
    while ($size > 0) {
        $block_info[] =[
            'size' => ($size >= $block_size ? $block_size : $size),
            'file' => $file_name . '.' . ($i++) . $ext
        ];
        $size -= $block_size;
    }

    $fp = fopen($file_path, "rb");
    foreach ($block_info as $bi) {
        $handle = fopen($bi['file'], "wb");
        fwrite($handle, fread($fp, $bi['size']));
        fclose($handle);
        unset($handle);
    }
    fclose($fp);
    unset($fp);

    return $block_info;
}

/**
 * 合并文件
 *
 * @param string $file_path 文件名
 * @param string $save_file 另存为的文件名
 */
function file_combine($file_path, $save_file = '') {
    $block_info = [];
    $ext        = file_ext($file_path);
    $file_name  = str_replace($ext, '', $file_path);
    for ($i = 0; ; $i++) {
        $split_file_path = $file_name . '.' . $i . $ext; 
        if (file_exists($split_file_path) && filesize($split_file_path) > 0) {
            $block_info[] = $split_file_path;
        } else {
            break;
        }
        
    }

    if ($save_file) {
        $fp = fopen($save_file, "wb");
    } else {
        $fp = fopen($file_path, "wb");
    }
    
    foreach ($block_info as $block_file) {
        $handle = fopen($block_file, "rb");
        fwrite($fp, fread($handle, filesize($block_file)));
        fclose($handle);
        unset($handle);
    }
    fclose($fp);
    unset($fp);
}

/**
 * 获取文件的扩展名
 *
 * @param string $filename 文件名
 * @return string
 */
function file_ext($filename) {
    if (empty($filename)) {
        return '';
    }
    return '.' . strtolower(trim(substr(strrchr($filename, '.'), 1)));
}

// 测试
$filename = 'D:\123\123456.zip';

// 分割
$ret = file_split($filename);
print_r($ret);

// 合并
file_combine($filename, 'D:\456\abcdef.zip');

 

 

参考:

https://www.jb51.net/article/138037.htm

https://www.cnblogs.com/yyjie/p/7181759.html