Model function:
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');
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)) :
$error = array('error' => $this->upload->display_errors());
var_dump($error);
return FALSE;
else :
$file = $this->upload->data();
$files[] = $file['file_name'];
endif;
endforeach;
if(empty($files)):
return FALSE;
else:
return implode(',', $files);
endif;
}
This function is working partially. Files are being uploaded to the selected folder, but I am getting this error: You did not select a file to upload. and getting FALSE as a result? What seems to be a problem? (form is using form_open_multipart)
Please make sure that you have this name of your file tag field:
$key='userfile' //which is name of input type field name
Are any of your file inputs empty when this happens? $_FILES will contain an array of "empty" data if there is no file specified for the input. For example, my file input name is one, and I submitted it without specifying a file:
Array
(
[one] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
You should check if the file data is empty before processing the upload. PHP's is_uploaded_file() is useful for this.
Related
In my CodeIgniter project, I'm uploading multiple files during the project creation. Please let me know how to upload multiple file using CI.
This is output array after submit form.
[user_attached] => Array
(
[name] => Array
(
[pic_passport] => cp-user-error.png
[att_document] => local-delivery-done.png
)
[type] => Array
(
[pic_passport] => image/png
[att_document] => image/png
)
[tmp_name] => Array
(
[pic_passport] => C:\xampp\tmp\phpC707.tmp
[att_document] => C:\xampp\tmp\phpC718.tmp
)
[error] => Array
(
[pic_passport] => 0
[att_document] => 0
)
[size] => Array
(
[pic_passport] => 635392
[att_document] => 36512
)
)
To Upload Multiple File in Codeigniter. Try this.
$filesCount = count($_FILES['user_attached']['name']);
$path = 'upload/document';
if (!file_exists($path)) {
mkdir($path, 0777, true);
}
$array = ['pic_passport','att_document'];
for($i = 0; $i < $filesCount; $i++) {
$_FILES['userFile']['name'] = $_FILES['user_attached']['name'][$array[$i]];
$_FILES['userFile']['name'] = $_FILES['user_attached']['name'][$array[$i]];
$_FILES['userFile']['type'] = $_FILES['user_attached']['type'][$array[$i]];
$_FILES['userFile']['tmp_name'] = $_FILES['user_attached']['tmp_name'][$array[$i]];
$_FILES['userFile']['error'] = $_FILES['user_attached']['error'][$array[$i]];
$_FILES['userFile']['size'] = $_FILES['user_attached']['size'][$array[$i]];
$imagename = $this->randomAlphanumId(10);
$image_name[$array[$i]]="doc_".$imagename."_".str_replace(array(' '),'_',$_FILES['userFile']['name']);
$config['upload_path'] = $path;
$config['allowed_types'] = '*';
$config['file_name'] = $image_name[$array[$i]];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('userFile')) {
$fileData = $this->upload->data();
$upload_image[] = $fileData['file_name'];
}
}
Create library for this code and call from controller
for($i = 0; $i < $config_array['files_count']; $i++)
{
if($config_array['file_data']['name'][$i])
{
$file_name = $config_array['file_data']['name'][$i];
$file_info = pathinfo($file_name);
$new_file_name = preg_replace('/[[:space:]]+/', '_', $file_info['filename']);
$new_file_name = $new_file_name.'_'.DATE(UPLOAD_FILE_DATE_FORMAT);
$new_file_name = str_replace('.','_',$new_file_name);
$file_extension = $file_info['extension'];
$new_file_name = $new_file_name.'.'.$file_extension;
$_FILES['attchment']['name'] = $new_file_name;
$_FILES['attchment']['tmp_name'] = $config_array['file_data']['tmp_name'][$i];
$_FILES['attchment']['error'] = $config_array['file_data']['error'][$i];
$_FILES['attchment']['size'] = $config_array['file_data']['size'][$i];
$config['upload_path'] = $config_array['file_upload_path'];
$config['file_name'] = $new_file_name;
$config['allowed_types'] = $config_array['file_permission'];
$config['file_ext_tolower'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['max_size'] = $config_array['file_size'];
$this->CI->load->library('upload',$config);
$this->CI->upload->initialize($config);
if($this->CI->upload->do_upload('attchment'))
{
array_push($file_array,array(
'og_name'=> $file_name,
'name'=> $new_file_name)
);
}
else
{
array_push($error_msgs,$this->CI->upload->display_errors('',''));
}
}
}
Am trying to include an image in a form, the image is added correctly but however two rows are added in the database table.
Structure of table with data added is below:
My controller
public function addRecordToTable(){
$this->load->library('form_validation');
$this->form_validation->set_rules('client_id' , 'client_id', 'required');
$this->form_validation->set_rules('l_address' , 'location address', 'required|min_length[3]|max_length[50]');
if ($this->form_validation->run() == false) {
$this->load->model('Clientaccount_model');
$data['bids']=$this->Clientaccount_model->bids();
$data['loads']=$this->Truckeraccount_model->loads();
$this->load->view('footer');
} else {
$array = array(
'client_id' => $this->input->post('client_id'),
'l_address' => $this->input->post('l_address'),
);
$record_id = $this->consignmentupload_model->addData('consignment', $array);
$this->uploadFiles($record_id);
}
}
public function uploadFiles($record_id){
$config = array(
'upload_path' => FCPATH . "/uploads/",
'allowed_types' => 'jpg|png|jpeg',
'overwrite' => TRUE,
);
$this->load->library('upload', $config);
$files = $_FILES['uploads'];
foreach ($files['name'] as $key => $filename) {
$_FILES['uploads[]']['name'] = $files['name'][$key];
$_FILES['uploads[]']['type'] = $files['type'][$key];
$_FILES['uploads[]']['tmp_name'] = $files['tmp_name'][$key];
$_FILES['uploads[]']['error'] = $files['error'][$key];
$_FILES['uploads[]']['size'] = $files['size'][$key];
$config['file_name'] = $filename;
$this->upload->initialize($config);
if (isset($_FILES['uploads[]']['name']) && !empty($_FILES['uploads[]']['name'])) {
if ( ! $this->upload->do_upload('uploads[]')) {
$error = array('error' => $this->upload->display_errors());
} else {
$uploads[] = $this->upload->data();
$array = array(
'record_id' => $record_id,
'filename' => $_FILES['uploads[]']['name'],
'size' => $_FILES['uploads[]']['size']
);
$this->consignmentupload_model->addData('consignment', $array);
}
}
}
redirect(site_url('clientaccount_ctrl'));
}
My Model
public function addData($table, $array)
{
$this->db->insert($table, $array);
return $this->db->insert_id();
}
after your first insert that is,
$record_id = $this->consignmentupload_model->addData('consignment', $array);
you have to update the same row with your image,
so in uploadFiles instead of, $this->consignmentupload_model->addData('consignment', $array);
make a new model function updateData() where you update the same row which was inserted earlier, pass the luggage_id to updateData()
i'm try to build REST API use codeigniter plugin from https://github.com/chriskacerguis/codeigniter-restserver
i'm successfull built multiple upload with this, but i have a trouble when upload many file data.
when i'm select 3 file in my directory, my code work, but in upload path i just have 2 file.
here controller :
function upload_post()
{
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
{
for($s=0; $s<=$count-1; ) {
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config['upload_path'] = 'E:/tes/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
$s++;
}
}
$names= implode(',', $name_array);
/* $this->load->database();
$db_data = array('id'=> NULL,
'name'=> $names);
$this->db->insert('testtable',$db_data);
*/ print_r($names);
print_r($count);
}
I have made a helper function for me which upload the files and return a array with upload result.It takes a parameter upload directory where to save the files. Here is the my function
function upload_file($save_dir="images")//takes folder name where to save.default images folder
{
$CI = & get_instance();
$CI->load->library('upload');
$config=array();
$config['upload_path'] = FCPATH.$save_dir;
$config['allowed_types'] = 'gif|jpg|png';//only images.you can set more
$config['max_size'] = 1024*10;//10 mb you can increase more.Make sure your php.ini has congifured same or more value like this
$config['overwrite'] = false;//if file do not replace.create new file
$config['remove_spaces'] = true;//remove sapces from file
//you can set more config like height width for images
$uploaded_files=array();
foreach ($_FILES as $key => $value)
{
if(strlen($value['name'])>0)
{
$CI->upload->initialize($config);
if (!$CI->upload->do_upload($key))
{
$uploaded_files[$key]=array("status"=>false,"message"=>$value['name'].': '.$CI->upload->display_errors());
}
else
{
$uploaded_files[$key]=array("status"=>true,"info"=>$CI->upload->data());
}
}
}
return $uploaded_files;
}
Sample output
if you print out the function returns you will get the output like this
Array
(
[file_input_name1] => Array
(
[status] => 1//status will be true if uploaded
[info] => Array //if success it will return the file informattion
(
[file_name] => newfilename.jpg
[file_type] => image/jpeg
[file_path] => C:/Program Files (x86)/VertrigoServ/www/rnd/images/
[full_path] => C:/Program Files (x86)/VertrigoServ/www/rnd/images/newfilename.jpg
[raw_name] => newfilename
[orig_name] => newfilename.jpg
[client_name] => newfilename
[file_ext] => .jpg
[file_size] => 762.53
[is_image] => 1
[image_width] => 1024
[image_height] => 768
[image_type] => jpeg
[image_size_str] => width="1024" height="768"
)
)
[file_input_name_2] => Array
(
[status] =>//if invalid file status will be false with error message
[message] => desktop.ini: <p>The filetype you are attempting to upload is not allowed.</p>
)
)
Hope it may help you
I want to put a restriction on the size of images uploaded.
Below I have condition for image size.
if ($_FILES["upload_attachment"]["size"] < 25000)) // Max File Size: 25KB
{
echo "File size exceeds maximum.";
}
I want insert condition in this code.
if ( $_FILES ) {
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post->ID);
}
}
}
}
Basically, you want to check that early, before you proceed with file processing, so you're not making the server do any work if it doesn't have to.
Also, FYI, the upload size is specified in bytes, so if you want 25KB, it will be (25 * 1024) = 25600 bytes.
To incorporate that condition, you could do this. It gets a little gnarly, so I've added comments on the closing brackets to note which closes what. fe = foreach
if ( $_FILES ) {//if files exist
if ($_FILES["upload_attachment"]["size"] < 25600) { // Max File Size: 25KB
//I would also recommend adding error handling early.
if ($_FILES['filename']['error'] > 0){
echo 'Error: ' . $_FILES['filename']['error'] . '<br />';
} else {
$files = $_FILES['upload_attachment'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array("upload_attachment" => $file);
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post->ID);
}//fe
}//if
}//fe
}//if no errors (else)
} //if size ok
else {
echo "File size exceeds maximum.";
}
}//if $_FILES
I'm absolutely stuck on this... checked all related stackoverflow posts and nothing has helped. Using Phil's REST Server / Client setup in Codeigniter and can insert normal entries but cannot upload multiple images, actually even a single image.
I can't really work out how to debug the REST part, it just returns nothing.
I have this array coming in from the view:
Array
(
[1] => Array
(
[name] => sideshows.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phppYycdA
[error] => 0
[size] => 967656
)
[2] => Array
(
[name] => the-beer-scale.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpCsiunQ
[error] => 0
[size] => 742219
)
[3] => Array
(
[name] => the-little-lace.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpXjT7WL
[error] => 0
[size] => 939963
)
[4] => Array
(
[name] => varrstoen-australia.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpcHrJXe
[error] => 0
[size] => 2204400
)
)
I am using this helper method I found to sort out multiple file uploads:
function multifile_array()
{
if(count($_FILES) == 0)
return;
$files = array();
$all_files = $_FILES['files']['name'];
$i = 0;
foreach ($all_files as $filename) {
$files[++$i]['name'] = $filename;
$files[$i]['type'] = current($_FILES['files']['type']);
next($_FILES['files']['type']);
$files[$i]['tmp_name'] = current($_FILES['files']['tmp_name']);
next($_FILES['files']['tmp_name']);
$files[$i]['error'] = current($_FILES['files']['error']);
next($_FILES['files']['error']);
$files[$i]['size'] = current($_FILES['files']['size']);
next($_FILES['files']['size']);
}
$_FILES = $files;
}
This function is being called within the API controller:
public function my_file_upload_post() {
if( ! $this->post('submit')) {
$this->response(NULL, 400);
}
$data = $this->post('data');
multifile_array();
$foldername = './uploads/' . $this->post('property_id');
if(!file_exists($foldername) && !is_dir($foldername)) {
mkdir($foldername, 0750, true);
}
$config['upload_path'] = $foldername;
$config['allowed_types'] = 'gif|jpg|png|doc|docx|pdf|xlsx|xls|txt';
$config['max_size'] = '10240';
$this->load->library('upload', $config);
foreach ($data as $file => $file_data) {
$this->upload->do_upload($file);
//echo '<pre>';
//print_r($this->upload->data());
//echo '</pre>';
}
if ( ! $this->upload->do_upload() ) {
return $this->response(array('error' => strip_tags($this->upload->display_errors())), 404);
} else {
$upload = $this->upload->data();
return $this->response($upload, 200);
}
}
I am happy to share my code, I did manage to get multiple files uploading no worries, but just trying to set it up with the API so I can call it from an external website, internally or an iPhone. Help would be appreciated.
Cheers
Update:
Here is the code from the API Controller:
function upload_post() {
$foldername = './uploads/' . $this->post('property_id');
if(!file_exists($foldername) && !is_dir($foldername)) {
mkdir($foldername, 0750, true);
}
$config['upload_path'] = $foldername;
$config['allowed_types'] = 'gif|jpg|png|doc|docx|pdf|xlsx|xls|txt';
$config['max_size'] = '10240';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
//return $this->response(array('error' => strip_tags($this->upload->display_errors())), 404);
return $this->response(array('error' => var_export($this->post('file'), true)), 404);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $this->response(array('error' => $data['upload_data']), 404);
}
return $this->response(array('success' => 'successfully uploaded' ), 200);
}
This works if you go directly to the API from the form, but you need to put in the username and password within the browser. If I run this via the controller then it can't find the images.
This is not exactly what you asked for, but this is what I used to solve this problem. A PHP/jQuery upload widget!
http://blueimp.github.com/jQuery-File-Upload/