<?php
class FileManger {
private static $instance = 0;
private $mainFile;
private $contents;
private $fileName;
private $filePath;
public $outputFileName;
private $chunkSize = 2000;
protected function __construct($fileName, $filePath, $chunkSize) {
$this->fileName = $fileName;
$this->filePath = $filePath;
$this->chunkSize = $chunkSize;
}
public static function getInstance($fileName, $filePath, $chunkSize) {
if(self::$instance == 0) {
self::$instance = new self($fileName, $filePath, $chunkSize);
}
return self::$instance;
}
public function splitFile() {
if ($this->fileName == '') {
return 'File name empty';
}
if($this->filePath == '') {
return 'File Path empty';
}
if($this->chunkSize == 0 ) {
return 'Chunk size empty';
}
if(file_exists($this->filePath . 'files')) {
rmdir($this->filePath . 'files');
}
mkdir($this->filePath . 'files',0777);
$this->mainFile = $this->filePath . $this->fileName;
$mainFileHandle = fopen($this->mainFile,'rb');
if($mainFileHandle === false) {
return 'Unable to open file';
}
while(!feof($mainFileHandle)) {
$this->contents = fread($mainFileHandle,$this->chunkSize);
$newFileName = $this->filePath . 'files/' . substr($this->fileName,0,strlen($this->fileName) - 4) . sprintf('%03d',$i++) . substr($this->fileName, -4);
$chunkFileHandle = fopen($newFileName,'wb');
fwrite($chunkFileHandle, $this->contents);
fclose($chunkFileHandle);
}
return "Success";
}
public function joinFile() {
$dirHandle = dir($this->filePath . 'files/');
$fileArray = Array();
while(false !== ($file = $dirHandle->read()) ){
if($file != '.' && $file != '..'){
$fileArray[] = $file;
}
}
if(!is_array($fileArray) && count($fileArray) < 1) {
return 'No Files';
}
$newFileHandle = fopen($this->filePath . $this->outputFileName, 'ab');
for($i = 0; $i < count($fileArray); $i++) {
//$this->chunkFileHandle = fopen($this->filePath . 'files/' . $fileArray[$i], 'r');
$this->contents = file_get_contents($this->filePath . 'files/' . $fileArray[$i]);
fwrite($newFileHandle, $this->contents);
unlink($this->filePath . 'files/' . $fileArray[$i]);
}
fclose($newFileHandle);
}
}
$filePath = dirname(__FILE__)."/";
$fileName = "1st.jpg";
$chunkSize = '20000';
$fileManger = FileManger::getInstance($fileName, $filePath, $chunkSize);
$fileManger->outputFileName = "newImage.jpg";
//$fileManger->splitFile();
//$fileManger->joinFile();
?>