Abu Sufian Abu Sufian - 3 years ago 220
PHP Question

Codeigniter 3.0: File name is not changing after uploading

I am uploading images and files through a form. But after the upload the name is not changing. On first function call if the name is i.e profilePic then this file name remains same on every call even i am changing the name in $config['file_name'] parameter.

Function calls:

function getAndSaveEmployeeDetails() {
$resume = 'resume';
$resume = $this -> do_upload($resume, $employeeID);

$profilePic = 'profilePic';
$profilePic = $this -> do_upload($profilePic, $employeeID);

$cnic = 'cnicScannedImage';
$cnicScannedImage = $this -> do_upload($cnic, $employeeID); }


//upload function

public function do_upload($uploadedField, $employeeID) {
//$uploadedField = $this -> input -> post('_hidden_field');
if (empty($_FILES[$uploadedField]['name'])) {

$error = "File is empty please choose a file";
return $error;

} else {
$name = '_' . $uploadedField;
$config['file_name'] = $employeeID . $name;
$config['upload_path'] = './uploads/' . $employeeID;
$config['allowed_types'] = 'gif|jpg|jpeg|png|iso|dmg|zip|rar|doc|docx|xls|xlsx|ppt|pptx|csv|ods|odt|odp|pdf|rtf|sxc|sxi|txt|exe|avi|mpeg|mp3|mp4|3gp';
$config['max_size'] = 2048;
$config['max_width'] = 0;
$config['max_height'] = 0;
$this -> load -> library('upload', $config);

if (!is_dir('uploads')) {
mkdir('./uploads', 0777, true);
}
$dir_exist = true;
// flag for checking the directory exist or not
if (!is_dir('uploads/' . $employeeID)) {
mkdir('./uploads/' . $employeeID, 0777, true);
$dir_exist = false;
// dir not exist
} else {

}

if (!$this -> upload -> do_upload($uploadedField)) {

if (!$dir_exist)
rmdir('./uploads/' . $employeeID);

$error = array('error' => $this -> upload -> display_errors());
return $error;

//$this -> load -> view('upload_form', $error);
} else {
$data = array('upload_data' => $this -> upload -> data());

return $path = $data['upload_data']['full_path'];

}
}
}


Please look at the image in the below link you will understand the behavior

These are the file names and it is caching the first name passed in function call

Answer Source

Load upload library in the first line of getAndSaveEmployeeDetails(), using

$this->load->library('upload');

without passing any config.

Then in do_upload($uploadedField, $employeeID) function after defining your config array, don't use $this->load->library('upload', $config); but use $this->upload->initialize($config);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download