I have a bit of the problem with file upload. I am trying to upload two files, but for some reason first file is being uploaded twice and there is no trace of the second file. What am I doing wrong?
Function for file upload (model):
public function file_upload($folder, $allowed_type, $max_size = 0, $max_width = 0, $max_height = 0)
{
$folder = $this->path . $folder;
$files = array();
$count = 0;
foreach ($_FILES as $key => $value) :
$file_name = is_array($value['name']) ? $value['name'][$count] : $value['name'];
$file_name = $this->global_functions->char_replace($file_name, '_');
$count++;
$config = array(
'allowed_types' => $allowed_type,
'upload_path' => $folder,
'file_name' => $file_name,
'max_size' => $max_size,
'max_width' => $max_width,
'max_height' => $max_height,
'remove_spaces' => TRUE
);
$this->load->library('image_lib');
$this->image_lib->clear();
$this->load->library('upload', $config);
if (!$this->upload->do_upload($key)) :
$error = array('error' => $this->upload->display_errors());
return FALSE;
else :
$file = $this->upload->data();
$files[] = $file['file_name'];
endif;
endforeach;
if(empty($files)):
return FALSE;
else:
return implode(',', $files);
endif;
}
Function form file upload (controller):
public function dokument_insert()
{
$this->admin_login_check();
$dokument =explode(',', $this->doc->file_upload('/doc', 'pdf|PDF|doc|docx') );
var_dump($dokument);
$data = array(
'naziv' => $this->input->post('naziv_srb'),
'opis' => $this->input->post('opis_srb'),
'path_pdf' => $dokument[0],
'path_doc' => $dokument[1],
'kategorija_id' => $this->input->post('kategorija'),
'jezik_id' => $this->input->post('jezik')
);
$this->doc->save($data);
}
Part of the form for files (view):
<label for="dokument_pdf">Dokument PDF</label>
<input type="file" name="pdf" id="dokument_pdf">
<label for="dokument_doc">Dokument DOC</label>
<input type="file" name="doc" id="dokument_doc">
You must to initialize the upload library with each upload.
$this->load->library('upload');
$this->upload->initialize($config);
User guide: https://www.codeigniter.com/user_guide/libraries/file_uploading.html
Looks like because you have 2 doc fields it will ANYWAY loop 2 times, whatever...
If you want only one you should send only one via the form OR don't use a ForEach and process each one manually each other with their fixed names.
Related
Here I am attaching the code of the desires problem.
Cotroller has following code.
Controller=>
//Load upload library
$this->load->library('upload');
$images = array();
$i = 0;
foreach ($_FILES as $key => $value)
{
$tmp = explode(".",$value['name'][$i]);
$imagename = time().".".end($tmp);
$_FILES['file']['name'] = $imagename;
$_FILES['file']['type'] = $value['type'][$i];
$_FILES['file']['tmp_name'] = $value['tmp_name'][$i];
$_FILES['file']['error'] = $value['error'][$i];
$_FILES['file']['size'] = $value['size'][$i];
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = $imagename;
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('file'))
{
$error = array($i => $this->upload->display_errors());
echo "<pre>";print_r($error);die;
}
else
{
array_push($images,$this->upload->data()['file_name']);
}
$i++;
}
echo "<pre>";print_r($images);die;
This is a form code that I am using while uploading file.
View =>
<?php $attributes = array(
"class" => "form-horizontal m-t-20",
"method" => "post",
"novalidate" => "",
"enctype" => "multipart/form-data"
);
echo form_open('admin/user/adduser', $attributes); ?>
Here is my file input control.
<label for="file">Profile Images*</label>
<input type="file" name="files[]" id="file" multiple required placeholder="Profile Images" class="form-control">
Change your code as follows
foreach($_FILES["files"]["tmp_name"] as $key=>$value) {
and change $i to the $key as follows (apply to the all)
$_FILES['file']['type'] = $_FILES["files"]['type'][$key];
As wazabii suggested, attached some random string to the file name. You can use rand(100,10000)
That is because the time() will be the same on all the images, so the file name is not unique. This is easily fixed by adding the array key to the file name.
$tmp = explode(".",$value['name'][$i]);
$imagename = time()."-".$key.".".end($tmp);
contoller code
public function upload_multiple($field_name,$path){
$this->load->library('upload');
$files = $_FILES;
$cpt = count($_FILES[$field_name]['name']);//count for number of image files
$image_name =array();
for($i=0; $i<$cpt; $i++)
{
$_FILES[$field_name]['name']= $files[$field_name]['name'][$i];
$_FILES[$field_name]['type']= $files[$field_name]['type'][$i];
$_FILES[$field_name]['tmp_name'] = $files[$field_name]['tmp_name'][$i];
$_FILES[$field_name]['error']= $files[$field_name]['error'][$i];
$_FILES[$field_name]['size'] = $files[$field_name]['size'][$i];
$this->upload->initialize($this->set_upload_options($path));//for initalizing configuration for each image
$this->upload->do_upload($field_name);
$data = array('upload_data' => $this->upload->data());
$image_name[]=$data['upload_data']['file_name'];//store file name to store in database
}
return $image_name;//all images name which is uploaded
}
public function set_upload_options($path)
{
$config = array();
$config['upload_path'] = $path;
$config['allowed_types'] = 'gif|jpg|png';
$config['overwrite'] = FALSE;
return $config;
}
function call
$image_name=$this->upload_multiple('portfolio_image',$path);//for multiple image upload
input field
<input type="file" id="portfolio_image" name="protfolio_image[]" >
while uploading docx, pdf file, The filetype you are attempting to upload is not allowed.
My add function is:-
public function add() {
$this->load->helper('ckeditor'); // for loading ckeditor
$this->load->library('form_validation');
$this->form_validation->set_rules($this->validation_rules);
if ($this->form_validation->run() == TRUE) {
$file_name = '';
if ($_FILES["file"]["size"] > 0) {
$this->load->library('upload', $this->fu_config);
if (!$this->upload->do_upload('file')) {
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('files/add', 'refresh');
} else {
$file = $this->upload->data();
$file_name = $file['file_name'];
}
}
// preparing for insertion
foreach ($this->validation_rules as $k => $v) {
$fields[] = $v['field'];
}
$data = $this->files_model->array_from_post($fields);
$data['file'] = $file_name;
if ($this->files_model->save($data)) {
$this->session->set_flashdata('success', 'New Event Added Successfully.');
} else {
$this->session->set_flashdata('error', 'sorry, Event cannot be Added.');
}
redirect('files/add/', 'refresh');
} else {
$files = new stdClass();
// Go through all the known fields and get the post values
foreach ($this->validation_rules as $key => $field) {
$files->$field['field'] = set_value($field['field']);
}
}
$data = array(
'method' => 'add',
'main_content' => 'form',
'editData' => $files,
'ckeditor' => array(
'id' => 'description',
'path' => 'js/ckeditor',
)
);
$this->load->view('admin_wrapper', $data);
}
I tried to change system/libraries/Upload.php line 199:
$this->_file_mime_type($_FILES[$field]);
Change that line to:
$this->_file_mime_type($_FILES[$field]); var_dump($this->file_type); die();
I got out put this: -
string(42) "cannot open `' (No such file or directory)"
How can i solve this error ?
make sure your $this->fu_config is correct,
example of the config :
$config['upload_path'] = './uploads/'; //Your file path for upload
$config['allowed_types'] = 'pdf|docx';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
I want to upload multiple files using codeigniter.
I have two types of images beforeimage and afterimage. After uploading each image I make entry in database.
I am creating thumbnail as well. To amke it ease I created a separate function, but its not working. this logic works for single image upload.
Html
controller
foreach($_FILES["beforepicture"]['name'] as $key=>$files){
//if(isset($_FILES["beforepicture"]['name']) && $_FILES["beforepicture"]['name'] != ''){
$imagestatus = $this->upload_images($files,'beforepicture');
if(isset($imagestatus['name'])){
$inputdata = array('image' => $imagestatus['name'],
'lead_id' =>$inserted_id,
'user_id'=>$this->session->userdata['userdata']['userid'],
'when'=>'before');
$this->common_model->save('lead_images',$inputdata);
//}
}
}
function upload_images($data = NULL,$inputname=NULL){
if($data){
$this->load->library('image_lib');
// echo '<pre>';
// print_r($_FILES);
$new_name = time().$data;
$config = array(
'upload_path' => getcwd()."/assets/themes/default/avatars/",
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
// 'max_height' => "768",
//'max_width' => "1024",
'file_name' => $new_name
);
$this->load->library('upload', $config);
$this->upload->initialize($config);
//$this->upload->initialize($config);
if($this->upload->do_upload($inputname))
{
$image_data = $this->upload->data();
//thumb1
$config = array(
'source_image' => $image_data['full_path'], //path to the uploaded image
'new_image' => getcwd()."/assets/themes/default/avatars/thumb", //path to
'maintain_ratio' => true,
'width' => 180,
'height' => 200
);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$message = array('name' => $image_data['file_name']);
}else
{
//echo $this->upload->display_errors(); die;
$message = array('failed' => $this->upload->display_errors());
}
return $message;
}
}
I am trying but failed
Try this
<?php
class My_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('upload');
}
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
}
$fileName = implode(',',$images);
$this->my_model->upload_image($fileName);
}
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = './upload/'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
}
For more how to upload multiple file in codeigniter try this tutorial:http://w3code.in/2015/09/upload-file-using-codeigniter/
Try this
$files = $_FILES;
$cpt = count($_FILES['beforepicture']['name']);
for($i=0; $i<$cpt; $i++){
$_FILES['beforepicture']['name']= $files['beforepicture']['name'][$i];
$_FILES['beforepicture']['type']= $files['beforepicture']['type'][$i];
$_FILES['beforepicture']['tmp_name']= $files['beforepicture']['tmp_name'][$i];
$_FILES['beforepicture']['error']= $files['beforepicture']['error'][$i];
$_FILES['beforepicture']['size']= $files['beforepicture']['size'][$i];
$imagestatus = $this->upload_images($_FILES["beforepicture"]['name'],'beforepicture');
if(isset($imagestatus['name'])){
$inputdata = array('image' => $imagestatus['name'],
'lead_id' =>$inserted_id,
'user_id'=>$this->session->userdata['userdata']['userid'],
'when'=>'before');
$this->common_model->save('lead_images',$inputdata);
}
}
How do we insert new file name after remaining in my database?
I have file with same name but different image example jellyfish.jpg and jellyfish.jpg.
After set 'overwrite' to set false and I try to upload jellyfish.jpg twice and successfully upload
the image in first name jellyfish.jpg and the second upload is jellyfish1.jpg in my folder uploads.
However, after I check in database, name of file is same jellyfish.jpg and jellyfish.jpg and not jellyfish.jpg and jellyfish1.jpg
How to insert new file name in my database?
Relevant controller code:
<?php
class Cutidiluar extends CI_Controller {
var $limit=10;
var $offset=10;
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('Cutidiluar_Model');
}
public function add()
{ if($this->session->userdata('LOGIN')=='TRUE')
{
$this->load->library('form_validation');
$this->load->model('Diluartahunan_Model');
$this->form_validation->set_rules('ket', 'ket');
$this->form_validation->set_rules('lama', 'lama');
$this->form_validation->set_rules('lampiran', 'lampiran');
if ($this->form_validation->run() == false) {
$data['nama'] = $this->Diluartahunan_Model->nama();
$data['view'] = 'Cutidiluar/add';
$data['judul']='';
$this->load->view('index',$data);
}else {
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => false,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload',$config);
$this->upload->do_upload();
$this->upload->data();
//file berhasil diupload -> lanjutkan ke query insert
$npp=$this->session->userdata('NPP');
$id_jenis = $_POST['id_jenis'];
$ket = $_POST['ket'];
$lama = $_POST['lama'];
$tgl_selesai= date('Y-m-d', strtotime($_POST['tgl_selesai']));
$tgl_mulai= date('Y-m-d', strtotime($_POST['tgl_mulai']));
$lampiran = $_FILES['userfile']['name'];
$data = array (
'npp'=> $npp,
'id_jenis'=> $id_jenis,
'tgl_pengajuan' => date('y-m-d'),
'ket' => $ket,
'status' => 'P',
'lampiran'=> $lampiran,
'lama'=> $lama,
'tgl_mulai'=> $tgl_mulai,
'tgl_selesai'=> $tgl_selesai,
);
$this->Cutidiluar_Model->add($data);
redirect('Cutidiluar');}}}
The file to upload
$lampiran = $_FILES['userfile']['name'];
*update (solved)
I'm change to this code
from
$lampiran = $_FILES['userfile']['name'];
to
$lampiran = $this->upload->file_name;
thanks to suggest editing my question and sorry for my lack english
Here's a simple function write inside the controller:
function incrementFileName($file_path,$filename){
if(count(glob($file_path.$filename))>0)
{
$file_ext = end(explode(".", $filename));
$file_name = str_replace(('.'.$file_ext),"",$filename);
$newfilename = $file_name.'_'.count(glob($file_path."$file_name*.$file_ext")).'.'.$file_ext;
return $newfilename;
}
else
{
return $filename;
}
}
Call this function before $config array as
$newName = $this->incrementFileName( "uploads/", $_FILES["my_file"]["name"]);
In $config array add 'file_name'=>$newName
This is my upload model
function upload_avatar()
{
$id = $this->tank_auth->get_user_id();
//config upload parameters and upload image
$config = array(
'allowed_types' => 'jpeg|jpg|png',
'upload_path' => $this->upload_path,
'max_size' => 2048,
'encrypt_name' => TRUE,
'overwrite' => FALSE,
);
$this->load->library('upload', $config);
$this->upload->do_upload();
//get upload data, config, resize uploaded image, save in avatars subfolder
$image_data = $this->upload->data();
if ($image_data['file_size'] < 2048) {
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->upload_path . '/avatars',
'maintain_ratio' => TRUE,
'width' => 125,
'height' => 125
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
//only burn avatar path to user_profiles table if no upload errors
if (!$this->upload->display_errors()) {
$data = array('avatar' => base_url() . 'images/avatars/' . $image_data['file_name']);
$this->db->where('id', $id);
$this->db->update('user_profiles', $data);
}
//delete the original file from server
$this->load->helper('file');
unlink($image_data['full_path']);
} else {
echo $this->upload->display_errors();
}
}
I can't get the error message to echo straight to the browser when I try uploading a file > 2MB.
To be fair, CI ignores this large file, and uploads correctly when a file is < 2MB.
The only thing is that I can't get the error message to show on the front-end to give the suer some feedback.
Any ideas what's wrong here?
$config['upload_path'] = 'uploads/category/'.$id.'/';
//echo $file_name;die;
//echo $config['upload_path'];
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '2048';
$config['max_width'] = '1920';
$config['max_height'] = '1280';
$this->load->library('upload');
foreach ($_FILES as $key => $value) {
//print_r($key);
if (!empty($key['name'])) {
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)) {
// echo 'test';die;
// rmdir('uploads/category/'.$id);
$errors = $this->upload->display_errors();
flashMsg($errors);
}
}
}
try this!!
Is your post_max_size limit less than 2MB? (http://ca3.php.net/manual/en/ini.core.php#ini.post-max-size) If so the file may have been discarded before your code is invoked.
Update:
If you take out your function call in the else block, and just drop in an exit('too big'); are you able to see errors then? If so there may be an issue with how you're pasing the call off.