Codeigniter, uploading multiple files with same name - php

I have an upload form that allows me to add as many files as needed. However when I start trying to upload the files I get an error.
Controller
$this->load->library('upload');
$error = "";
$file = "";
$this->total_count_of_files = count($_FILES['user_certificates']['name']);
print_r($_FILES['user_certificates']['name']);
for($i=0; $i<$this->total_count_of_files; $i++)
{
$_FILES['user_certificates']['name'] = $_FILES['user_certificates']['name'][$i];
$_FILES['user_certificates']['type'] = $_FILES['user_certificates']['type'][$i];
$_FILES['user_certificates']['tmp_name'] = $_FILES['user_certificates']['tmp_name'][$i];
$_FILES['user_certificates']['error'] = $_FILES['user_certificates']['error'][$i];
$_FILES['user_certificates']['size'] = $_FILES['user_certificates']['size'][$i];
$config['encrypt_name'] = TRUE;
$config['file_name'] = $_FILES['user_certificates']['name'];
$config['upload_path'] = './certificate_files/';
$config['allowed_types'] = 'txt|pdf|doc|docx';
$config['max_size'] = 0;
$this->upload->initialize($config);
if (!$this->upload->do_upload())
{
$status = 'error';
$msg = $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
$file = $data['raw_name'] . $data['file_ext'];
}
if($file)
{
$status = "success";
$msg = "Image successfully uploaded";
}
else
{
$status = "error";
$msg = "Something went wrong when saving the image, please try again.";
}
}
echo json_encode(array('status' => $status, 'msg' => $msg));
exit();
The print_r($_FILES['user_certificates']['name'])) shows me the files I have added:
Array ( [0] => license.txt [1] => license.txt )
I am totally stuck on how to get the upload to work. Any ideas?
Cheers in advance!
EDIT
If I change this:
if (!$this->upload->do_upload())
to this:
if (!$this->upload->do_upload('user_certificates'))
it works, but only for one file, it doesn't seem to loop round again for some reason

Your loops seems to be incorrect.
...
$_FILES['user_certificates']['name'] = $_FILES['user_certificates']['name'][$i];
...
these lines overwrite the original $_FILES array, so after completion of first loop, it will not find anything else in the loop because it got overwritten.
Instead you may first store the $_FILES array to a local variable and loop through it to upload one by one.

Related

Uploading a file to a custom path in codeigniter

I'm trying to upload a file but I keep getting a "The upload path does not appear to be valid." error. The problem is the path I'm trying to upload to is in the directory just outside the current one. The current folder structure is as follows:
application
assets
- uploads
- profile_pictures
Admin
- application
- assets
I am attempting to upload a picture from the admin application into the 'assets/uploads/profile_pictures' folder which is in the main application root directory. The only issue is correcting the path.
Here's the code from the Controller:
public function update_image(){
$user_id= $this->input->post('user_id');
//$user_id=$this->input->post('user_id');
$query5 = $this->db->get_where('user_details', array('user_id' => $user_id));
$name_user = $query5->row()->name;
$name='profile_image_edit';
$user_img=$this->function->upload_profile_images(array($name), $name_user);
var_dump($user_img);
$this->db->set("image_path",$user_img);
$this->db->where("user_id",$user_id);
$update = $this->db->update("users");
if($update)
{
echo 'Profile Image Updated.';
}
else
{
echo 'Profile Image Update Failed.';
}
}
And here's the code from the Model:
public function upload_profile_images($names, $username)
{
$config['upload_path']='./assets/uploads/profile_pictures';
$config['allowed_types']='jpeg|jpg|png';
$path = $_FILES[$names[0]]['name'];
var_dump($names[0]);
var_dump($path);
$ste_d =date('YmdHis') . gettimeofday()['usec'];
$newName = str_replace("",'',str_replace("",'',"$ste_d.str_replace(" ",'_',str_replace(".","",pathinfo($path, PATHINFO_FILENAME)))."_muddy.")).pathinfo($path, PATHINFO_EXTENSION);
$config['file_name'] = $username ."_". $newName;
$this->upload->initialize($config);
$this->load->library('upload', $config['upload_path']);
$check = true;
for($i = 0; $i < count($names) && $check; $i++)
{
if ( ! $this->upload->do_upload($names[$i]))
{
$path='./assets/uploads/profile_pictures';
$this->load->helper("file");
$error = array('error' => $this->upload->display_errors());
var_dump($error);
// delete_files($path, true);
$check = false;
return false;
}
else
{
$data = array('upload_data' => $this->upload->data());
$check = true;
return 'assets/uploads/profile_pictures'.'/'.$data['upload_data']['file_name'];
}
}
}
How do I set a custom path so the file is always saved in the desired directory of assets/uploads/profile_pictures from the Admin application. Thanks for any help!

How to delete old file from the folder while updating?

I want to delete the old file from the folder ie, if I update an image the old one remains as it is in the folder and a new one is get uploaded.
Here updating is done fine but after frequent updating number of files is increasing .
This is the code for selecting the content from the database and also for updating
public function select_testimonials($id)
{
$this->session->set_userdata('id',$id );
$query = $this->cl_testimonials_model->select($id);
$data1['selectdata'] = $query->result();
// $this->index();
$query = $this->db->get("cl_testimonials");
$data1['records'] = $query->result();
$this->load->view('admin/testimonials/testimonials_edit',$data1);
}
public function update_testimonials()
{
$id = $this->input->post("id");
if ($this->input->post('submit')=="update")
{
if(!empty($_FILES['picture']['name']))
{
$config['upload_path'] = 'uploads/images/testimonials';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('picture'))
{
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
}
}
//Prepare array of user data
$data = array('name' => $this->input->post('name'),'content' => $this->input->post('content'),'picture' => $picture);
//Pass user data to model
$insertUserData = $this->cl_testimonials_model->update($id,$data);
}
//Storing insertion status message.
if(isset($insertUserData))
{
$data['message']="* testimonials updated successfully.";
}
else
{
$data['message']="* Some problems occured, please try again.";
}
$query = $this->db->get("cl_testimonials");
$data['records'] = $query->result();
$this->load->view('admin/testimonials/testimonials_listing',$data);
}
Fetch Existing testimonial picture path by id, update, then use unlink('old file path')
More here : Here
Use the unlink(); function in php. it is applicable also in Codeigniter.
unlink("target path/".$file name);

how can i check the value of a variable from a controller in codeigniter

I am doing an upload image file in CodeIgniter. I want to trace out the image in my code and update my database path with it. I want to print the $image_path variable in the code below where it was located in my controller.
How can I print the $image_path variable to display or check its value inside the controller or maybe echo it out ?
Here it is:
<?php
public function upload_file()
{
$status = "";
$msg = "";
$file_element_name = 'userfile';
if ($status != "error") {
$config['upload_path'] = './assets/upimages/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = FALSE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
$image_path = $data['full_path'];
if(file_exists($image_path))
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
?>
If I understand the question your asking then you want to view the contents of the $image_path variable.
If all you want is to check this then you could pass it back to the view with the json array ('image_path' => $image_path).
The other option is to var_dump($image_path) however to view this you would need to inspect the post data response on the browser and it may also stop the json from working while you are using the var_dump().
Blinky
try echo $image_path; or print_r($image_path)

Codeigniter two file upload, one mandatory and one optional

I am trying to upload two files with the help of codeigniter functions.
One of the file should be mandatory and one should be optional.
I am using the code below to upload those files but I cannot figure out the way to make one optional and one mandatory. I tried few modifications to the code below, but i bumped into many errors. I am new to codeigniter.
Even the code below for handling the uploads may not be appropriate but it is working.
$config['upload_path'] = 'uploads/';
$path=$config['upload_path'];
$config['allowed_types'] = '*';
$this->load->library('upload');
$i=0;
foreach ($_FILES as $key => $value)
{
if (!empty($key['name']))
{
$this->upload->initialize($config);
if (!$this->upload->do_upload($key))
{
$errors = $this->upload->display_errors();
$this->session->set_flashdata('error', $errors);
redirect(base_url().'upload', 'refresh');
}
else
{
$data = array('upload_data' => $this->upload->data());
$p[$i] = $this->upload->data();
}
}
$i++;
} //endforeach
if(empty($errors)){
//if there are no errors, write it into the database
$data = array('user_id'=>$this->session->userdata('id'),
'name'=>$this->input->post('name'),
'screenshot'=>$p[1]['file_name'],
'model'=> $p[0]['file_name'],
'created'=>date('Y-m-d H:i:s')
);
if($this->usermodel_model->save($data)){
//success
redirect(base_url().'dashboard?success');
}else{
//failed
redirect(base_url().'upload');
}
}
Sohanmax put $i++; inside if (!empty($key['name'])){ } and after ending foreach check if($i !=0) if it's false show the error, hope it'll work.

Codeigniter Multiple File Upload Encryption Issue

I've got a big form that allows users to upload multiple files/filetypes to an offer/bid they are creating. Everything is working fine except one piece: the name encryption of the files before saving to the database.
I haven't found a rhyme or reason for it, but it's hit or miss. The image works fine every time. The other documents (which allow all [*] types, but primarily will consist of various business docs such as pdf, doc, xls, etc.) are the ones that are spotty.
I found threads on SO and elsewhere about general issues with the name encryption but have yet to come across one that deals with the specificity of my issue.
Here's the upload function:
//for multi uploads
function do_uploads($name, $file)
{
$status ="";
$msg = "";
$file_element_name = $name;
//go through and figure out where it goes
if($name == "QuoteDoc") {
$folder = "quotedocs";
$allowed = '*';
}
else if($name == "ProductOfferPhoto") {
$folder = "product_photos";
$allowed = 'jpeg|jpg|png|gif';
}
else if($name == "ResearchWhtPaper1" || $name == "ResearchWhtPaper2") {
$folder = "research";
$allowed = "*";
}
else if($name == "ProductLiterature1" || $name == "ProductLiterature2") {
$folder = "literature";
$allowed = "*";
}
else if ($name == "FDALink") {
$folder = "fda";
$allowed = "*";
}
$config['upload_path'] = './uploads/' . $folder;
$config['allowed_types'] = $allowed;
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else {
$data = $this->upload->data();
}
#unlink($_FILES[$file_element_name]);
//what's up?
//return $this->upload->data();
return array('status' => $status, 'msg' => $msg, 'data' => $this->upload->data(), 'allowed'=>$allowed);
}
Any help would be greatly appreciated.
You're not stating your question very clearly:
Are the names simply not being encrypted, but still uploading to the correct directories?
Are you setting these inside a loop, where perhaps the class instance is not being re-initialized? Does the first file encrypt correctly, but not the subsequent ones?
Can you track which file types are not working correctly?
I have trouble believing it is completely "random", and think there's just not enough research being done here
Solution from below:
You need to use $this->upload->initialize($config) to change the config, as the library will only be loaded once

Categories