file name changes when i upload i file using do_upload function - php

when i upload a file using do_upload() in code igniter, it uploads the file but it renames it with underscore(_) in the place of blank spaces.
file name to be uploaded: A B C.pdf
file that uploads: A_B_C.pdf
code in controller to upload file:
//$filefeild is the name of folder in which file is to be saved
public function upload_Files($filefeild)
{
//set preferences
$config['upload_path'] = 'assets/bcc/'.$filefeild."/";
$config['allowed_types'] = 'doc|docx|xml|pdf|image|excel|jpg|png|jpeg';
$config['max_size'] = 0;
$config['filname'] = $filenamee = $_FILES[$filefeild]['name'];
$this->upload->initialize($config);
if (!$this->upload->do_upload($filefeild))
{
// case - failure
$upload_error = array('error' => $this->upload->display_errors());
}
else
{
// case - success
$upload_data = $this->upload->data();
$data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . $upload_data['file_name'] . '</strong> was successfully uploaded!</div>';
$filname = $upload_data['file_name'];
return $filenamee;
}
}

IF you see codeigniter's function exist here, you will find following code,
// Remove white spaces in the name
if ($this->remove_spaces === TRUE)
{
$this->file_name = preg_replace('/\s+/', '_', $this->file_name);
}
Which means codeigniter removes spaced and adds _ by default which can be changed by setting config variable. like $config['remove_spaces'] = FALSE;
Secondly if you want your file should be saved with underscors and you get actual name by which file is being saved then in your code you have to make a slight change as described below.
your current code
$config['filname'] = $filenamee = $_FILES[$filefeild]['name'];
Change it to
$config['filname'] = $_FILES[$filefeild]['name'];
and in success scenario get file name from $this->upload->data()
Note: you can find answere here aswell.

Related

adding timestamp while uploading image file is not working

I am developing a ad site that anyone able to upload 3 images.
So I am coding to upload that 3 images by adding timestamp in front of their file name to make them unique. I use codeigniter framework and attaching the code below.
when I submitting form data, localhost server shows that images have been saved correctly with some code infornt of image filename. But problem is there are no images saved in relevant image folder in that name and I cannot retrieve that images in next preview advertisement page.
I don't know much about php or codeignitor. Your help is highly appreciated.
$config['upload_path'] = './assets/images/adsimages';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5120;
$this->load->library('upload',$config);
$this->upload->initialize($config);
if (!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'no_image.jpg';
}
else {
$data = array('upload_data' => $this->upload->data());
$post_image1 = time().$_FILES['userfile1']['name'];
$post_image2 = time().$_FILES['userfile2']['name'];
$post_image3 = time().$_FILES['userfile3']['name'];
}
$result = $this->post_model->adregister($post_image1,$post_image2,$post_image3);
You can append time to 'filename' in config of upload library
$config['file_name'] = time().$_FILES['userfile1']['name'];
Or if you want unique name for all files the simply add
$config['encrypt_name'] = TRUE;
then
$this->load->library('upload', $config);
Try this one:-
$path = pathinfo($_FILES["userfile1"]["name"]);
$image_path = $path['filename'].'_'.time().'.'.$path['extension'];
I've written a possible solution for your code. You haven't shared your full code so you'll have to fill in the gaps yourself and maybe make some changes here and there; Comments are mentioned wherever necessary. See if it helps you.
public function your_function_name(){
// your-code
// your-code
// check if file is uploaded in field1
if(!empty($_FILES['userfile1']['name'])){
// call function to upload file
$userfile1 = $this->upload_file('userfile1');
}
// check if file is uploaded in field2
if(!empty($_FILES['userfile2']['name'])){
$userfile2 = $this->upload_file('userfile2');
}
// check if file is uploaded in field3
if(!empty($_FILES['userfile3']['name'])){
$userfile3 = $this->upload_file('userfile3');
}
$result = $this->post_model->adregister($userfile1, $userfile2, $userfile3);
}
// function to upload file
function upload_file($filename){
$config['file_name'] = time().$_FILES[$filename]['name']; // append time to filename
$config['upload_path'] = './assets/images/adsimages';
$config['allowed_types'] = 'gif|jpg|jpeg|png|GIF|JPG|PNG|JPEG';
$config['max_size'] = 5120;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$uploaded = $this->upload->do_upload($filename);
if ( ! $uploaded ){
$error = array('error' => $this->upload->display_errors());
$file = 'no_image.jpg'; // default file
}else{
$upload_data = $this->upload->data();
$file = $upload_data['file_name']; // uploaded file name
}
return $file; // return filename
}

How do you upload image into database in Code igniter?

I've been trying to upload an image to my database (Note: I'm using Codeigniter 3) but every time I try to upload the image to the database it doesn't store it's filename and the image itself and only stores 1 bit in BLOB var type.
$photo = file_get_contents($_FILES['image']['tmp_name];
this->db->select('*')
[...]
if(empty($response){
$data['entry_phone_no'] = $this->input->post('phone_no');
$data['entry_email'] = $this->input->post('email');
$data['entry_firstname'] = $this->input->post('first_name');
$data['entry_lastname'] = $this->input->post('last_name');
$data['entry_photo'] = $photo;
$data['entry_photo_name'] = $photo;
In my model.php I have the setup above and it saves the other data (the phone num, email etc). I know I am missing some code at the "$photo" part but can anyone please point it out?
You can upload the image on folder called "Uploads" and save that filename into database as below:
Views.php:
<input class="my-set_3" type="file" name="chatbot_profile" id="chatbot_profile" required>
Controller.php:
if (!empty($_FILES['chatbot_profile']['name']))
{
$config['upload_path'] = './uploads';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1000000;
$config['file_name'] = time();
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('chatbot_profile'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$file_name = $data['upload_data']['file_name'] ;
// Store this filename into database
// Your database code will be placed here
// OR call model mathod from here
}
}
Note: uploads folder will created by us and outside the application
folder.

How to delete old images from uploads folder after inserting insert a new image

I am able to overwrite the image in the database but the old images still remains in the assets folder.
How can I delete the previous image from the assests folder when i insert a new one?
Please explain in a bit of details since i am a beginner.
public function image_insert(){
$id=1;
if ($this->input->post('submit') && !empty($_FILES['body_image']['name'])) {
$body_image = $_FILES['body_image']['name'];
if($body_image != NULL){
$config['upload_path'] = './assets/image/';
$config['log_threshold'] = 1;
$config['allowed_types'] = 'jpg|png|jpeg|gif';
$config['max_size'] = '0'; // 0 = no file size limit
$config['overwrite'] = true;
$this->load->library('upload', $config);
$this->upload->do_upload('body_image');
$upload_data = $this->upload->data();
$body_image = $upload_data['file_name'];
}
$this->Home_model->insert_image($body_image,$id);
redirect(base_url('landing_page/home_edit'));
}
else {
redirect(base_url('landing_page/home_edit'));
}
}
If you want to delete a file which already exists in your image folder.
Suppose your image folder path is: /assets/image/
Then, the image delete code will be something like this.
$filePath="/assets/image/";
$fileName=$filePath."dummy.jpg";
if (file_exists($fileName))
{
unlink($fileName);
}
The above code will call you before uploading the image in upload folder.
you may use File helper to delete file :-
$this->load->helper('file');
$path='./assets/image/'.$file_name;
delete_files($path);

How to rename more than 1 file during upload ? Codeigniter

I have a form to upload about 5 files,
lets say it is a photo of the person who is registering and other document about him.
now i'm creating a folder for every registered user with their name ( btw, is it good thing to do? ), and i want to rename each file with the right name let say photo,document A,document B and etc.
my current code
$upload_setting['upload_path'] = './uploads/'.$_POST['name'].'/';
$upload_setting['allowed_types'] = 'jpg|pdf';
$upload_setting['max_size'] = 5000; // 5 MB
$upload_setting['file_name'] = $_POST['name']; // this define the uploaded file name
$this->load->library('upload', $upload_setting);
if ($this->form_validation->run() == FALSE){
$this->load->view('form');
}
else{
if (!is_dir('./uploads/'.$_POST['name'].'/')) {
mkdir('./uploads/'.$_POST['name'].'/', 0777, TRUE);
}
$this->member->register($this->input->post(NULL, TRUE));
$this->upload->do_upload('photo');
$this->upload->do_upload('document-A');
$this->upload->do_upload('document-B');
Also how can i let them free to upload JPG,PDF,DOC ?
i have to link these file in their profile page.
how can i know what extension they upload for each document ?
Please let me know if you have any suggestion or best practice to do this upload and then display each upload in their profile.
Thanks
To know the extension of your file you can use-
$newname= "name";
$path_parts = pathinfo($_FILES["picture"]["name"]);
$file_newname = $newname.'.'.$path_parts['extension'];
To Upload-
if( $_FILES['picture']['name'] )
{
$config['upload_path'] = 'images/receipt/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['file_name'] = $file_newname; //Here your file is being renamed
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('picture'))
{
$error = array('error' => $this->upload->display_errors());
return false;
}
}

Delete uploaded file with a wrong name as the defined

Below is my upload function in codeigniter. I can upload a file. I also check if the file name matches the url parameter. How do i delete the file if the name does not match the url. I have tried unlink function but it does not work
function do_upload() {
$this->makeDir();
$labref = $this->uri->segment(3);
$filename = 'xyz/'. date('Y').'/'.date('M').'/'. $labref .'/' . $labref . '.xlsx';
if (file_exists($filename)) {
$data['labref'] = $this->uri->segment(3);
$data['settings_view'] = 'analyst_file_present_v';
$this->base_params($data);
} else {
$config['upload_path'] = 'xyz/'. date('Y').'/'.date('M').'/'. $labref ;
$config['allowed_types'] = 'xls|xlsx';
$this->load->library('upload', $config);
$data= $this->upload->data();
if ($data['file_name']=="$labref.'.xlsx'") {
$this->SaveFileDetails();
$this->success();
}else{
$filename = 'xyz/'.date('Y').'/'.date('M').'/'. $labref.'/'.$labref.'xlsx' ;
unlink($filename);
echo 'You have uploaded a wrong file';
}
if (!$this->upload->do_upload('worksheet')) {
$data['labref'] = $this->uri->segment(3);
$data['error'] = $this->upload->display_errors();
$data['settings_view'] = 'upload_analyst_v';
$this->base_params($data);
}
}
}
You've got some pretty nasty quote mismatches:
if ($data['file_name']=="$labref.'.xlsx'") {
^-----^---
Since you're in a double-quoted string, those ' are going to become part of the filename. Perhaps you meant:
if ($data['file_name']== $labref .'.xlsx') {
instead? (note lack of ".
It seems to me you are trying to delete the wrong file.
You should replace:
$filename = 'xyz/'.date('Y').'/'.date('M').'/'. $labref.'/'.$labref.'xlsx' ;
with:
$filename = 'xyz/'.date('Y').'/'.date('M').'/'. $labref.'/' . $data['file_name'];
To delete the uploaded file.
Edit: You have to actually do the upload before you can access the errors and data so you should move your $this->upload->do_upload() block to before the if statement.

Categories