Codeigniter Rename file on upload
In CodeIgniter, you can rename a file on upload by using the do_upload()
method of the Upload
class. This method allows you to specify various options for uploading a file, including the new name for the file. Here is an example of how to use this method to rename a file on upload:
<?php
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = 'neuer_dateiname';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$error = ['error' => $this->upload->display_errors()];
$this->load->view('upload_form', $error);
} else {
$data = ['upload_data' => $this->upload->data()];
$this->load->view('upload_success', $data);
}
In this example, the $config
array is used to set the upload path, allowed file types, and the new file name. Then the upload
library is loaded and the do_upload()
method is used to upload the file. The do_upload()
method returns a boolean value indicating whether the upload was successful or not. If the upload is successful, the data()
method of the Upload
class can be used to retrieve information about the uploaded file, such as its name, size, and type.
You can also use the rename()
method of the Upload
class to rename a file after it has been uploaded. This method takes the original file name and the new file name as arguments and returns a boolean value indicating whether the rename was successful or not.
<?php
$original_name = $this->upload->data('file_name');
$new_name = 'new_file_name.jpg';
if ($this->upload->rename($original_name, $new_name)) {
echo 'File successfully renamed!';
}
It is important to remember that the rename method will only work if the move_uploaded_file is set to false in the config file.