if (!empty($_FILES)) {
// Set filename and upload path
$tempFile = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$targetPath = getcwd() . '/uploads/';
$targetFile = $targetPath . $fileName;
$initialFileName = $fileName;
// Get file info to get file name
$path_parts = pathinfo($targetFile);
// Duplicate file counter
$fileIncrement = 1;
// Prevent rewriting of existing documents with the same name
while (file_exists($targetFile) && $fileIncrement < 50) { // Limit to 50 duplicate files for safety.
// 1 increment will likely be enough
// If file with the name exists add '-file-1' continue increment by replacing last increment
$pattern = '/(.+)-attachment-(\d)+/i';
$replacement = '${1}';
$originalFilename = preg_replace($pattern, $replacement, $path_parts['filename']);
// Prepare new filename and file path
$fileName = $originalFilename . '-attachment-' . $fileIncrement . '.' . $path_parts['extension'];
$targetFile = $targetPath . $fileName;
// Prepare next increment
$fileIncrement += 1;
}
// Moves temporary file to new location
move_uploaded_file($tempFile, $targetFile);
if ($file_id = $this->attachments_model->add_attachment(array('filename' => $fileName, 'original_filename'=>$initialFileName, 'file_size' => $fileSize))) {
return $this->output
->set_content_type('application/json')
->set_status_header(200)
->set_output(json_encode(array('filepath' => $targetFile, 'file_id' => $file_id, 'file_name'=>$fileName)));
}
}else{
//
return $this->output
->set_content_type('application/json')
->set_status_header(200)
->set_output(json_encode(array('success' => false)));
}