Multiple form upload: get each file name separately in codeigniter - php

I want to upload some files. I use codeigniter:
Html:
<input type="file" name="file1" />
<input type="file" name="file2" />
php:
$config['upload_path'] = './upload/';
$path = $config['upload_path'];
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['encrypt_name'] = 'TRUE';
$this->load->library('upload', $config);
foreach ($_FILES as $key => $value) {
if (!empty($value['tmp_name']) && $value['size'] > 0) {
if (!$this->upload->do_upload($key)) {
// some errors
} else {
// Code After Files Upload Success GOES HERE
$data_name = $this->upload->data();
echo $data_name['file_name'];
}
}
}
When I want to echo file name, I get 1.jpg and 2.jpg. But I want to have them separately and insert them into database.
How can I do this? Thank you :)

Add the the value from $data_name['file_name'] into an array and after your foreach loop do a insert_batch.
something like:
$filename_arr = array();
foreach ($_FILES as $key => $value) {
if (!empty($value['tmp_name']) && $value['size'] > 0) {
if (!$this->upload->do_upload($key)) {
// some errors
} else {
// Code After Files Upload Success GOES HERE
$data_name = $this->upload->data();
$filename_arr[] = $data_name['file_name'];
}
}
}
$this->db->insert_batch('mytable', $filename_arr);

Related

how to upload multiple image with different input file in codeigniter

I want to upload multiple image with different input file with array name.
view :
<form action="" enctype="multipart/form-data" method="post">
<input name="picture[]" class="form-control" style="padding-top: 0;" type="file"/>
<input name="picture[]" class="form-control" style="padding-top: 0;" type="file"/>
<input type='submit' value="upload" />
</form>
controller:
public function index($id=null)
{
$id = $this->input->get('id');
if ($_POST)
{
if ($this->validation())
{
$file = $this->upload_picture();
if ($file['status'] == 'success')
{
echo $this->upload->data('file_name');
}
else
{
echo $file['data'];
echo $file['status'];
$this->session->set_flashdata('alert', alert('error', $file['data']));
}
}
else
{
$this->session->set_flashdata('alert', alert('error', validation_errors()));
}
//redirect($this->agent->referrer());
}
}
private function upload_picture()
{
$config['upload_path'] = './assets/img/page/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['max_size'] = 125000; // 1 GB
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('picture[]'))
{
return array(
'status' => 'error',
'data' => $this->upload->display_errors()
);
}
else
{
$data = $this->upload->data();
$resize['image_library'] = 'gd2';
$resize['source_image'] = './assets/img/page/'.$data['file_name'];
$resize['maintain_ratio'] = TRUE;
// $resize['width'] = 1920;
// $resize['height'] = 1080;
$this->load->library('image_lib', $resize);
$this->image_lib->resize();
return array(
'status' => 'success',
'data' => $this->upload->data()
);
}
}
private function validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('picture[0]', 'Picture', 'trim');
$this->form_validation->set_rules('picture[1]', 'Picture', 'trim');
$this->form_validation->set_error_delimiters('', '<br>');
return $this->form_validation->run();
}
result in browser always show error that mean return status to error in upload_picture function, I want to get filename that encrypted and store to database like a4b8a0e070128b0a3dabd9e2931f7ae3.jpg not picture.jpg.
codeigniter upload class doesn't support array file name in this way. So either you have to modify upload class file (not recommended to modify core class file), or you have to modify your codes.
You can name the inputs like this: picture_1, picture_2 etc.
In that case, modify upload_picture() method like this way:
foreach($_FILES as $key=>$val){
if(!$this->upload->do_upload($key)){
$return[$key] = $this->upload->display_errors(); //store this in an array and return at the end. array structure is up to you
}else{
$return[$key] = $this->upload->data(); //store this in an array and return at the end. array structure is up to you
}
}
return $return; //
This way you are uploading files one by one using the loop. However, you have to also modify main method as now it is returning multidimensional array. I've given you just an idea...

store multiple files at their specific fields in database with codeigniter

I am creating a form with 20+ fields to submit the details of the employee's. In the form the employee has to fill their details and upload their document. There are five fields for documents namely (photo,idcard,licence,cv,attest) so the name of each uploaded document has to be stored in a particular field . If i upload all the files in sequence then it is working fine but how to insert the name of a file to their designated field if the employee only inserts one or two files.
Hope i am making sense.
controller
public function register()
{
//form validation
if($this->form_validation->run() === False){
$this->load->view('form');
}
else{
//uploading files
$number_of_files = sizeof(array_filter($_FILES['file']['tmp_name']));
$files = $_FILES['file'];
$errors = array();
for($i=0;$i<$number_of_files;$i++)
{
if($_FILES['file']['error'][$i] != 0)
{
$error[$i] = array('error' => 'Couldn\'t upload file '.$_FILES['file']['name'][$i]);
$this->load->view('form',$error);
}
}
//create a new directory for each new user
$dir = $this->input->post('fname').'_'.$this->input->post('country');
if( is_dir(FCPATH . 'uploads/'.$dir) === false )
{
mkdir(FCPATH . 'uploads/'.$dir);
}
$this->load->library('upload');
$config['upload_path'] = FCPATH . 'uploads/'.$dir;
$config['allowed_types'] = 'gif|jpg|png|docx';
for ($i = 0; $i < $number_of_files; $i++) {
$_FILES['file']['name'] = $files['name'][$i];
$_FILES['file']['type'] = $files['type'][$i];
$_FILES['file']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['file']['error'] = $files['error'][$i];
$_FILES['file']['size'] = $files['size'][$i];
$this->upload->initialize($config);
// we retrieve the number of files that were uploaded
if ($this->upload->do_upload('file'))
{
$data['uploads'][$i] = $this->upload->data();
}
else
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('form',$error);
}
}
//assign names of uploaded files to insert in database
if($data){
foreach($data as $value){
$photo = FCPATH . 'uploads/'.$dir.$value[0]['file_name'];
$idProof = FCPATH . 'uploads/'.$dir.$value[1]['file_name'];
$cv = FCPATH . 'uploads/'.$dir.$value[2]['file_name'];
$license = FCPATH . 'uploads/'.$dir.$value[3]['file_name'];
$attest = FCPATH . 'uploads/'.$dir.$value[4]['file_name'];
}
}
$this->form_model->insert_users($photo,$idProof,$cv,$license,$attest);
redirect('form/registered');
}
}
model
public function insert_users($photo,$idProof,$cv,$license,$attest){
$data = array(
//other fields...
'other' => $this->input->post('other'),
'photo' => $photo,
'idProof' => $idProof,
'cv' => $cv,
'license' => $license,
'attest' => $attest
);
return $this->db->insert('employee',$data);
}
View
<input type='file' name='file[]' onchange="readURL(this);" />
<input type='file' name='file[]' onchange="readURL(this);" />
<input type='file' name='file[]' onchange="readURL(this);" />
<input type='file' name='file[]' onchange="readURL(this);" />
<input type='file' name='file[]' onchange="readURL(this);" />

Upload More then one image in codeigniter

I Have created a Form which contains 3 input(type["file"])
Student_Image, Father_Image, Mother_Image
I want to Upload Images in a folder, and Name Images According to me, and also save that image name into database.
you must add more than 1 image at time if your controller should be like this
public function upload_image($table_id){
$this->data['table_id'] = $table_id;
$this->data['data'] = $this->your_model->get($table_id);
if($this->input->post()) {
$upload_image = true;
$upload_path = FCPATH.'/uploads/upload_image';
$uploadedImageName = array();
for ($i=1;$i<=5;$i++){
$field_name ='image'.$i;
$temp_file_names = $this->file[$field_name]['name'];
if(isset($temp_file_names) && $temp_file_names!=''){
$file_name = time().'_'.$this->randomString(10).'.'.$this->getFileExtension($temp_file_names);
if(!$this->uploadImage($upload_path,$file_name,$field_name)){
$this->session->set_flashdata('error', $this->file_error);
} else {
$uploadedImageName[] = $this->file_data['file_name'];
}
} else {
$uploadedImageName[] = $this->input->post('old_image'.$i);
}
}
$update_data = array('Student_Image'=>json_encode($uploadedImageName));
if(!$this->your_model->updateimage($table_id,$update_data)){
$this->session->set_flashdata('error', 'Record couldn\'n updated. Please try again.');
} else {
$this->session->set_flashdata('success', 'Update successfully.');
redirect('/upload_image/'.$table_id);
}
}
$this->load->view('/upload_image',$this->data);
}
and
model
public function updateimage($table_id,$data){
$sql ="update tablename set ";
$update_data = array();
if(empty($data)){
return false;
}
public function get($table_id){
$sql ="select * from tablename where table_id = ?";
$rs = $this->db->query($sql,array($table_id));
$record = $rs->result();
return (array)$record[0];
}
$config['upload_path'] = 'uploads/images/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '2000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$data = [];
$errors = [];
foreach ($this->input->post('files') as $file_name)
{
if ($this->upload->do_upload($file_name))
{
$data[$file_name] = $this->upload->data();
}
else
{
$errors[$file_name] = $this->upload->display_errors();
}
}
Use below function
function upload_image()
{
$img1 = $this->_upload_image('Student_Image','YOUR_FOLDER_PATH','jpg|png|jpeg|gif',3000);
if($img1['status']){$filename1 = $img1['filename'];}
$img2 = $this->_upload_image('Father_Image','YOUR_FOLDER_PATH','jpg|png|jpeg|gif',3000);
if($img2['status']){$filename2 = $img2['filename'];}
$img3 = $this->_upload_image('Mother_Image','YOUR_FOLDER_PATH','jpg|png|jpeg|gif',3000);
if($img3['status']){$filename3 = $img3['filename'];}
}
function _upload_image($userfile,$image_path,$allowed,$max_size)
{
if($_FILES[$userfile]['name']!='')
{
if(!is_dir($image_path))
{
mkdir($image_path);
}
$config['upload_path'] = $image_path;
$config['allowed_types'] = $allowed;
$config['max_size'] = $max_size;
$img=$_FILES[$userfile]['name'];
$random_digit=rand(00,99999); //here you can change file name
$ext = strtolower(substr($img, strpos($img,'.'), strlen($img)-1));
$file_name=$random_digit.$ext;
$config['file_name'] = $file_name;
$this->ci->load->library('upload', $config);
if($this->ci->upload->do_upload($userfile))
{
return array('status'=>TRUE,'filename'=>$this->ci->upload->file_name);
}
else {return array('status'=>FALSE,'error'=>$this->ci->upload->display_errors('<span>','</span>'));}
}
}
you can try like this
$errors= array();
foreach($_FILES['gallery']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['gallery']['name'][$key];
$file_size =$_FILES['gallery']['size'][$key];
$file_tmp =$_FILES['gallery']['tmp_name'][$key];
$file_type=$_FILES['gallery']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$desired_dir="assets/images/products/";
$array=array('pid'=>$insert_id,'imagepath'=>$desired_dir.$file_name);
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
$this->db->insert('mx_products_images',$array);
}
}
<?php echo form_open_multipart('upload_controller/do_upload');?>
<div class="profilethumb">
<h4>Student's Image</h4>
<input type="file" name="S_image" id="image" class="btn btn-primary">
</div><!--profilethumb-->
<div class="profilethumb">
<h4>Father's Image</h4>
<br><input type="file" name="F_image" class="btn-primary"><br>
</div><!--profilethumb-->
<div class="profilethumb">
<h4>Mother's Image</h4>
<br><input type="file" name="M_image" class="btn-primary"><br>
</div><!--profilethumb-->
<div class="profilethumb">
<h4>Local Guardian Image</h4>
<br><input type="file" name="LG_image" class="btn-primary"><br>
</div><!--profilethumb-->
<input type="submit" value="submit detail" class="btn-primary" />
<?php echo "</form>"?>
This is my From details.. upload images into upload folder and save images name into S_Info Table into database.

How to Upload the image and Video in two Different Folder using Codeigniter

I am fresher in codeignite and I want to Upload the image and video into image and video folder. But image and video uploaded into the same folder.
I tried so many times using if condition, but nothing is changed.
Please help to solve this problem.
Here is my code:-
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$data['data'] = "";
$data['content']=$this->load->view('cmsblock/cmsblock',$data,TRUE);
$this->load->view('includes/main',$data);
}
function do_upload()
{
foreach ($_FILES as $key => $value) {
if (!empty($value['tmp_name'])) {
if($key == "file1") {
$config['upload_path'] = 'uploads';
$config['allowed_types'] = 'mp4|3gp|gif|jpg|png|jpeg|pdf';
$config['max_size']='';
$config['max_width']='200000000';
$config['max_height']='1000000000000';
$this->load->library('upload',$config);
if ( ! $this->upload->do_upload($key)) {
$error = array('error' => $this->upload->display_errors());
//failed display the errors
} else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('cmsblock/success', $data);
}
}
if($key == "file2") {
$config11['upload_path'] = 'videos';
//$config11['upload_path'] = 'uploads';
$config11['allowed_types'] = 'mp4|3gp|gif|jpg|png|jpeg|pdf';
$config11['max_size']='';
$config11['max_width']='200000000';
$config11['max_height']='1000000000000';
$this->load->library('upload',$config11);
if ( ! $this->upload->do_upload($key)) {
$error = array('error' => $this->upload->display_errors());
//failed display the errors
} else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('cmsblock/success', $data);
}
}
}
}
}
} ?>
Here is my HTML file code:
<?php echo form_open_multipart('admin/upload/do_upload');?>
<input type="file" name="file1" id="file_1" />
<input type="file" name="file2" id="file_2"/>
<br/><br/>
<input type="submit" value="upload" />
</form>
try using
$this->upload->initialize($config11);
instead of
$this->load->library('upload',$config11);
in if($key == "file2"){... part

Multiple upload and resize class.upload.php

I'm trying to upload multiple image to the server and to make different resolution version of each image.
To do this I'm using class.upload.php for the first time. http://www.verot.net/php_class_upload.htm
I look at the documentation and starting from the demo example http://www.verot.net/php_class_upload_download_zip.htm
I made a form with multiple input
<form name="form3" enctype="multipart/form-data" method="post" action="upload.php">
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p><input type="file" size="32" name="my_field[]" value="" /></p>
<p class="button"><input type="hidden" name="action" value="multiple" />
<input type="submit" name="Submit" value="upload" /></p>
</form>
the original php from the example only upload the image without resizing them:
$files = array();
foreach ($_FILES['my_field'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
// now we can loop through $files, and feed each element to the class
foreach ($files as $file) {
// we instanciate the class for each element of $file
$handle = new Upload($file);
// then we check if the file has been uploaded properly
// in its *temporary* location in the server (often, it is /tmp)
if ($handle->uploaded) {
// now, we start the upload 'process'. That is, to copy the uploaded file
// from its temporary location to the wanted location
// It could be something like $handle->Process('/home/www/my_uploads/');
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
// everything was fine !
echo 'ok';
} else {
// one error occured
echo ' Error: ' . $handle->error . '';
}
} else {
// if we're here, the upload file failed for some reasons
// i.e. the server didn't receive the file
echo ' Error: ' . $handle->error . '';
}
}
What I'd like to do is to process each file inside the if ($handle->processed) {}
so I took the function form the example that resize img and paste it inside the if ($handle->processed) {} part. Now it look like this:
if ($handle->uploaded) {
// now, we start the upload 'process'. That is, to copy the uploaded file
// from its temporary location to the wanted location
// It could be something like $handle->Process('/home/www/my_uploads/');
// now, we start a serie of processes, with different parameters
// we use a little function TestProcess() to avoid repeting the same code too many times
function TestProcess(&$handle, $title) {
global $dir_pics, $dir_dest;
$handle->Process($dir_dest);
// we check if everything went OK
if ($handle->processed) {
// everything was fine !
echo 'ok';
} else {
// one error occured
echo ' Error: ' . $handle->error . '';
}
}
if (!file_exists($dir_dest)) mkdir($dir_dest);
// ----------- save the uploaded img adding _xl to the name
$handle->file_name_body_add = '_xl';
$handle->file_overwrite = true;
TestProcess($handle, 'File originale', '');
// ----------- save the uploaded img adding _l to the name and downsizing it
$handle->file_name_body_add = '_l';
$handle->image_resize = true;
$handle->image_ratio_y = true;
$handle->image_x = 1024;
$handle->file_overwrite = true;
TestProcess($handle, 'Ridimensionato a 1024px');
}
At this point the script works fine only with the first img.
it not make the "foreach ($files as $file)" trow the $files array...
could you help my find where the error is?
thaks
Daniele
Creator of the class here... You need to change the $files array first, as following. It is in the FAQ:
$files = array();
foreach ($_FILES['my_field'] as $k => $l) {
foreach ($l as $i => $v) {
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
}
}
Okay, so i tried to use verot's answer but i got ALOT of errors, i tried other answers around the web.
Here is the working solution.
$placeDir = $_SERVER['DOCUMENT_ROOT'] . '/myuploadfolder';
$files = [];
foreach ($_FILES['image_field']['name'] as $key => $value) {
if(!empty($_FILES['image_field']['name'][$key])){
$name = $_FILES['image_field']['name'][$key];
$type = $_FILES['image_field']['type'][$key];
$tmp = $_FILES['image_field']['tmp_name'][$key];
$error = $_FILES['image_field']['error'][$key];
$size = $_FILES['image_field']['size'][$key];
$files[] = [
'name' => $name
, 'type' => $type
, 'tmp_name' => $tmp
, 'error' => $error
, 'size' => $size
];
}
}
foreach($files as $file){
$image = new uploadHelper($file);
$image->allowed = array('image/*');
if ($image->uploaded) {
$image->process($placeDir);
if ($image->processed) {
echo 'image done';
$image->clean();
} else {
echo 'error : ' . $image->error;
}
} else {
echo '<h1>IMAGE NOT UPLOADED</H1>';
}
}
I really hope this helps people out there.

Categories