The initial steps in this function are to create a handle to open the file, define a file size to be used in the function (in bytes), and define the part size: $handle = fopen($file_name, 'rb') or die("error opening file"); $file_size =filesize($file_name); $parts_size = floor($file_size/$parts_num); $modulus=$file_size % $parts_num; fopen uses 'rb' because it needs to only read the file in binary mode, which does not alter or translate the original data preserving its type. $part_size is a variable that contains the whole number of parts (round down using the floor function). If there is a remainder, it is assigned to the $modulus variable. Once the file is open, PHP will need to read the file according to the set part size and modulus. for($i=0;$i<$parts_num;$i++) { if($modulus!=0 & $i==$parts_num-1) $parts[$i] = fread($handle,$parts_size+$modulus) or die("error reading file"); else $parts[$i] = fread($handle,$parts_size) or die("error reading file"); } //close file handle fclose($handle) or die("error closing file handle"); The reading process is a loop that iterates based on the number of split parts ($parts_num). Once the file has been read, you need to write the file (this will actually create the parts of the split file). for($i=0;$i<$parts_num;$i++) { $handle = fopen('splited_'.$i, 'wb') or die("error opening file for writing"); fwrite($handle,$parts[$i]) or die("error writing splited file"); } //close file handle fclose($handle) or die("error closing file handle"); return 'OK'; } It still iterates based on the split parts ($parts_num). And now the file created will start with 'splited_', and will be placed in the same folder as splitthisfile.php is located. (See previous screenshots) The final splitthisfile() function will be: function splitthisfile($file_name,$parts_num) { $handle = fopen($file_name, 'rb') or die("error opening file"); $file_size =filesize($file_name); $parts_size = floor($file_size/$parts_num); $modulus=$file_size % $parts_num; for($i=0;$i<$parts_num;$i++) { if($modulus!=0 & $i==$parts_num-1) $parts[$i] = fread($handle,$parts_size+$modulus) or die("error reading file"); else $parts[$i] = fread($handle,$parts_size) or die("error reading file"); } //close file handle fclose($handle) or die("error closing file handle"); //writing to splitted files for($i=0;$i<$parts_num;$i++) { $handle = fopen('splited_'.$i, 'wb') or die("error opening file for writing"); fwrite($handle,$parts[$i]) or die("error writing splited file"); } //close file handle fclose($handle) or die("error closing file handle"); return 'OK'; } To call the function in the script: splitthisfile($file_name,$parts_num) or die('Error spliting file'); This ends the first part. In the second part you will learn how to create the merging script and actually implement those files in your FTP server. You can download the complete script from the second part.
blog comments powered by Disqus |
|
|
|
|
|
|
|