Example of Large File Cutting and Merging Function Implemented by PHP

  • 2021-09-20 19:40:07
  • OfStack

This paper describes the cutting and merging functions of large files realized by PHP. Share it for your reference, as follows:

Split code

split.php


<?php
$i  = 0;                 // Split block number 
$fp  = fopen("hadoop.sql","rb");      // File to split 
$file = fopen("split_hash.txt","a");    // Record the text file of segmented information, which exists in the actual production environment redis More appropriate 
while(!feof($fp)){
    $handle = fopen("hadoop.{$i}.sql","wb");
    fwrite($handle,fread($fp,5242880));// Size of cut block  5m
    fwrite($file,"hadoop.{$i}.sql\r\n");
    fclose($handle);
    unset($handle);
    $i++;
}
fclose ($fp);
fclose ($file);
echo "ok";

Merge code

merge.php


<?php
$hash = file_get_contents("split_hash.txt"); // Read the information of the split file 
$list = explode("\r\n",$hash);
$fp = fopen("hadoop2.sql","ab");    // Merged file name 
foreach($list as $value){
  if(!empty($value)) {
    $handle = fopen($value,"rb");
    fwrite($fp,fread($handle,filesize($value)));
    fclose($handle);
    unset($handle);
  }
}
fclose($fp);
echo "ok";

For more readers interested in PHP related contents, please check the special topics of this site: "php File Operation Summary", "PHP Common Traversal Algorithms and Skills Summary", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithms Summary", "PHP Array (Array) Operation Skills Complete Book", "php String (string) Usage Summary" and "php Common Database Operation Skills Summary"

I hope this article is helpful to everyone's PHP programming.


Related articles: