Splitting File into Parts in PHP

ManzZup's Avatar author of Splitting File into Parts in PHP
This is an article on Splitting File into Parts in PHP in PHP.
Rated 5.00 By 1 users
Recently i had to implement a file split-er in PHP and was shocked find how LESS pre written scripts are available for the task. So thought of writing a quick one myself.

If you just want the code, I have a fully featured php script hosted at github
Just download it there and well CONTRIBUTE


  1. Take the URL of the base file [we donot write the file upload part]
  2. Take the size of a part of the file [lets call it buffer]
  3. Read a buffer size of amount from the file till end-of-file is reached
  4. For every read part, write it as a seperate file
  5. For clarity the naming of files go like input_file_name.part<no>
    ex: myawesomefile.png.part0 myawesomefile.png.part1

The Code

PHP Code:
 * A file splitter function for php
 * Can split a file to number of parts depending on the buffer size given
 * @author manujith pallewatte [manujith.nc@gmail.com]
 * @date   30/10/13
 *  *
 * @param  $file String
 * Path of the file to split
 * @param $buffer number
 * The [maximum] size of the part of a file
 * @return array S
 * et of strings containing the paths to the parts
function fsplit($file,$buffer=1024){
//open file to read
$file_handle fopen($file,'r');
//get file size
$file_size filesize($file);
//no of parts to split
$parts $file_size $buffer;
//store all the file names
$file_parts = array();
//path to write the final files
$store_path "splits/";
//name of input file
$file_name basename($file);
//read buffer sized amount from file
$file_part fread($file_handle$buffer);
//the filename of the part
$file_part_path $store_path.$file_name.".part$i";
//open the new file [create it] to write
$file_new fopen($file_part_path,'w+');
//write the part of file
//add the name of the file to part list [optional]
//close the part file handle
//close the main file handle   

Most of the code is documented but i'll get into some important areas. First few lines are about taking in the filename, extracting the basename [thefile.exe part]

Next we find the number of parts to make
no_of_parts = size_of_file / buffer_size

Then we loop through 0 - no_of_parts in each loop we read a portion of the input file. Now the question is why php wont read the same portion always. It's simple, because when reading a file php keeps a pointer as to well where it is reading now. Thus when we tell it to read the second time, it simply start to read from the point it stopped previously

Convenient huh?

So DONE! You now have a complete splitter written in php - https://github.com/ManZzup/phpfsplit and you are free to carry it anywhere