I am working on a Social Network application with Codeigniter 3, Ion-Auth and Bootstrap 4. You can see the Github repo HERE.
I now have:
if ($this->form_validation->run() === TRUE)
{
//more code here
$config['upload_path'] = './assets/img/avatars';
$config['file_ext_tolower'] = TRUE;
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 1024;
$config['max_width'] = 1024;
$config['max_height'] = 1024;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')){
$error = array('error' => $this->upload->display_errors());
$file_name = null;
} else {
$file_name = $this->upload->data('file_name');
}
$additional_data = [
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'avatar' => $file_name,
'company' => $this->input->post('company'),
'phone' => $this->input->post('phone'),
];
}
The code above correctly hashes the filename before inserting it in the avatar
column, but the upload itself never happens.
I am uploading a user image (avatar) with the code below:
if ($this->form_validation->run() === TRUE)
{
//more code here
$config['upload_path'] = './assets/img/avatars';
$config['file_ext_tolower'] = TRUE;
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 1024;
$config['max_width'] = 1024;
$config['max_height'] = 1024;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')){
$error = array('error' => $this->upload->display_errors());
$file_name = null;
} else {
// get filename with extension
$file_name = $_FILES['userfile']['name'];
// get filename without extension
$file_name_clean = explode('.', $file_name)[0];
// get filename extension
$file_ext = explode('.', $file_name)[1];
//Add timestamp to filename and hash it
$file_name = md5($file_name.date('m-d-Y_H:i:s'));
// add extension
$file_name = $file_name_clean . '.' . $file_ext;
}
$additional_data = [
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'avatar' => $file_name,
'company' => $this->input->post('company'),
'phone' => $this->input->post('phone'),
];
}
As you can see in the else block, I am changing the original filename by adding it the current timestamp and hashing.
The problem is that the image file itself is not renamed accordingly before the upload. It is uploaded with the original name (the image is not stored in /assets/img/avatars/
).
Why does that happen?
if Use UPLOAD library
$config['encrypt_name'] = TRUE;
Don't use $_FILES
Change
$file_name = $_FILES['userfile']['name'];
To
$file_name = $this->upload->data('file_name');
And config.php Add directly your path
$config['base_url'] = "http://localhost/yourname/";