Multiple files uploading not working in Codeigniter - php

While uploading the multiple files in codeigniter i am getting error like this,
Fatal error: Unsupported operand types in .../system\libraries\Upload.php
if(isset($_FILES['med_file']))
{
$config['upload_path'] = './medical_history_doc/';
$config['allowed_types'] = 'jpg|jpeg|png|doc|docx|pdf|txt';
$this->load->library('upload', $config);
$files = $_FILES;
$cpt = count($_FILES['med_file']['name']);
for($i=0; $i<$cpt; $i++)
{
if($files['med_file']['name'][$i] !="")
{
$_FILES['med_file']['name']= $files['med_file']['name'][$i];
$_FILES['med_file']['type']= $files['med_file']['type'][$i];
$_FILES['med_file']['tmp_name']= $files['med_file']['tmp_name'][$i];
$attachment_name=$files['med_file']['name'][$i];
$path_info=pathinfo($attachment_name);
$file_extension=#$path_info['extension'];
$path_part_filename=$path_info['filename'];
$rename_file=str_replace(" ","",$path_part_filename).'_'.date('Ymdhis');
if(!empty($rename_file))
{
$_FILES['med_file']['name'] = $rename_file.'.'.$file_extension;
$medical_history_files[]=$rename_file.'.'.$file_extension;
if($this->upload->do_upload('med_file'))
{
$file_upload='true';
}
else if(!$this->upload->do_upload('med_file'))
{
$file_upload="fail";
$error= $this->upload->display_errors();
$this->session->set_flashdata('sucess', $error);
}
}
}
}
}
}
and my view page code is like this.
<form method="post" name="medicalhistory" id="medicalhistory"
enctype="multipart/form-data">
<input id="med_file" type="file" name="med_file[]" multiple>
</form>
Please help me how to solve this problem. Thanks

You missed a couple of things here.. First of all, your HTML form should have the attribute action pointing to your controller method. Second, the $_FILES array should always contain the following: name, type, tmp_name, error, size, however, in your loop you are only rebuilding with name, type, tmp_name, and you are forgetting the others. You are also renaming the file prior its being sent to the upload library. You should do this by setting it in the config array that is being sent to the library. I would redo you code in the following manner:
Step 1: Make sure the HTML form has the action attribute:
<form action="<?= base_url()?>controller/upload" ..
Step 2: Retrieve the files and unset the original $_FILES so that you can rebuild the array:
$uploaded_files = $_FILES['med_file'];
unset($_FILES);
Step 3: loop through the obtained files and rebuild the $_FILES array into a multidimensional array:
foreach ($uploaded_files as $desc => $arr) {
foreach ($arr as $k => $string) {
$_FILES[$k][$desc] = $string;
}
}
Step 4: Load the Upload library, and set your config options
$this->load->library('upload');
$config['upload_path'] = './medical_history_doc/';
$config['allowed_types'] = 'jpg|jpeg|png|doc|docx|pdf|txt';
Step 5: Loop through the new $_FILES array, rename you file and set the config['filename'] to the new name. Initialize your upload, then run it:
foreach ($_FILES as $k => $file) {
$path_info = pathinfo($file["name"]);
$file_extension = $path_info['extension'];
$path_part_filename = $path_info['filename'];
$config['file_name'] = str_replace(" ", "", $path_part_filename) . '_' . date('Ymdhis') . '.' . $file_extension;
$this->upload->initialize($config);
if (!$this->upload->do_upload($k)) {
$errors = $this->upload->display_errors();
var_dump($errors);
} else {
var_dump("success");
}
}
FINAL RESULT:
View:
<form action="<?= base_url()?>controller/upload" method="post" id="medicalhistory" enctype="multipart/form-data">
<input id="med_file" type="file" name="med_file[]" multiple>
<input type="submit">
</form>
Controller:
public function upload() {
$uploaded_files = $_FILES['med_file'];
unset($_FILES);
foreach ($uploaded_files as $desc => $arr) {
foreach ($arr as $k => $string) {
$_FILES[$k][$desc] = $string;
}
}
$this->load->library('upload');
$config['upload_path'] = './medical_history_doc/';
$config['allowed_types'] = 'jpg|jpeg|png|doc|docx|pdf|txt';
foreach ($_FILES as $k => $file) {
$path_info = pathinfo($file["name"]);
$file_extension = $path_info['extension'];
$path_part_filename = $path_info['filename'];
$config['file_name'] = str_replace(" ", "", $path_part_filename) . '_' . date('Ymdhis') . '.' . $file_extension;
$this->upload->initialize($config);
if (!$this->upload->do_upload($k)) {
$errors = $this->upload->display_errors();
var_dump($errors);
} else {
var_dump("success");
}
}
}

Related

upload multiple files with move_uploaded_file() function by using foreach loop

I'm trying to upload multiple files with for each loop. what should I use in the first parameter of move_uploaded_file() function in this case
foreach ($_FILES["prodImg"]["name"] as $pImage) {
$nbr++;
$col = 'image' . $nbr;
$fileName = basename($pImage);
$target_file = $target_dir . "" . $fileName;
$rqt = "UPDATE prodimages SET $col=? WHERE prodId= ? ";
$stmt = $con->prepare($rqt);
$stmt->execute(array($fileName, $pID));
move_uploaded_file($pImage, $target_file);
}
As you can see in the docs you can use $_FILES["prodImg"]["tmp_name"][$i]:
foreach ($_FILES["prodImg"]["name"] as $i => $pImage) {
move_uploaded_file($_FILES["prodImg"]["tmp_name"][$i], /*..*/);
}
You can always var_dump($_FILES); to see what it looks like.

php copy file for each filename in array

I am trying to move all the files in my array from one directory to another.
I have done some research and are using the php Copy() function.
here is my code so far:
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$myArray = explode(',', $filenameArray);
$finalArray = print_r($myArray);
function copyFiles($finalArray,$sourcePath,$savePath) {
for($i = 0;$i < count($finalArray);$i++){
copy($sourcePath.$finalArray[$i],$savePath.$finalArray[$i]);}
}
Anyone see where I'm going wrong?
Thanks in advance!
This is the unlink ive been attempting to use.
function copyFiles($finalArray,$sourcePath,$savePath) {
foreach ($finalArray as $file){
if (!copy($sourcePath.$file,$savePath.$file)) {
echo "Failed to move image";
}
$delete[] = $sourcePath.$file;
}
}
// Delete all successfully-copied files
foreach ( $delete as $file ) {
unlink( $sourcePath.$file );
}
My Final Working Code
the code below moves images in comma seperated array to new folder and removes them from current folder
$finalArray = explode(',', $filenameArray);
function copyFiles($finalArray,$sourcePath,$savePath) {
foreach ($finalArray as $file){
if (!copy($sourcePath.$file,$savePath.$file)) {
echo "Failed to move image";
}
}
}
copyFiles( $finalArray, $sourcePath, $savePath);
function removeFiles($finalArray,$sourcePath) {
foreach ($finalArray as $file){
if (!unlink($sourcePath.$file)) {
echo "Failed to remove image";
}
}
}
removeFiles( $finalArray, $sourcePath);
In your code you are not calling the copyFile function. Try this:
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$finalArray = explode(',', $filenameArray);
function mvFiles($finalArray,$sourcePath,$savePath) {
foreach ($finalArray as $file){
if (!rename($sourcePath.$file,$savePath.$file)) {
echo "failed to copy $file...\n";
}
}
}
mvFiles( $finalArray, $sourcePath, $savePath);
A simple solution :
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$myArray = explode(',', $filenameArray);
$finalArray = $myArray; //corrected this line
function copyFiles($finalArray, $sourcePath, $savePath)
{
for ($i = 0; $i < count($finalArray); $i++)
{
copy($sourcePath.$finalArray[$i],$savePath.$finalArray[$i]);
}
}
Hope you have right call to function copyFiles().
UPDATE for unlink() :
Let me try to throw some light on your work (written code):
foreach ($finalArray as $file)
{
if (!copy($sourcePath.$file,$savePath.$file))
{
echo "Failed to move image";
}
$delete[] = $sourcePath.$file;
}
Contents of $delete :
a. /source/img1.png
b. /source/img2.png
c. /source/img3.png
Now,
foreach ( $delete as $file )
{
unlink( $sourcePath.$file );
}
unlink() will be called with the following parameters:
$sourcePath.$file : /source/./source/img1.png : /source//source/img1.png => No such path exists
$sourcePath.$file : /source/./source/img2.png : /source//source/img2.png => No such path exists
$sourcePath.$file : /source/./source/img3.png : /source//source/img3.png => No such path exists
$sourcePath.$file : /source/./source/img4.png : /source//source/img4.png => No such path exists
I think for this reason, unlink is not working.
The code to be written should be like the following:
foreach ( $delete as $file )
{
unlink( $file );
}
Now, unlink() will be called with the following parameters:
a. /source/img1.png => path do exists
b. /source/img2.png => path do exists
c. /source/img3.png => path do exists
Do tell me if this does not solves the issue.
Update as per Dave Lynch's code:
$filenameArray = "img1.png,img2.png,img3.png";
$sourcePath = "/source/";
$savePath = "/newDir/";
$finalArray = explode(',', $filenameArray);
foreach ($finalArray as $file)
{
$delete[] = $sourcePath.$file;
}
foreach ( $delete as $file )
{
echo $sourcePath.$file . "</br>";
}
Output:
/source//source/img1.png
/source//source/img2.png
/source//source/img3.png
Please check.
Thanks and Regards,

How can I catch Codeigniter multiple file upload error?

I'm using Codeigniter for uploading files. It's working fine when I meet the file requirements. The problem is, I want to display the errors if ever there is one, but my page only refreshes when there is an error. Here is my code (I only got the code from the web and revised it):
foreach($_FILES['userfile'] as $key=>$val)
{
$i = 1;
foreach($val as $v)
{
$field_name = "file_".$i;
$_FILES[$field_name][$key] = $v;
$i++;
}
}
$err = 0;
$i=0;
// Unset the useless one ;)
unset($_FILES['userfile']);
$config['file_name'] = time();
$config['upload_path'] = './uploads/events';
$config['allowed_types'] = 'pdf';
$config['max_size'] = '200000';
$this->load->library('upload',$config);
foreach($_FILES as $field_name => $file)
{
if ($this->upload->do_upload($field_name))
{
$upload_data = $this->upload->data(); //UPLOAD FILES TO FOLDER
$this->Upload_items->files($upload_data['file_name']); //WRITE TO DATABASE;
}else{
echo $this->upload->display_errors();
}
$i++;
if(($i==$ctr)&&($err==0)){
$this->Upload_items->event(); //WRITE TO MULTIMEDIA TABLE
}
}
The functions to write to the database are not yet done, btw.
EDIT: The error for allowed_types is displaying, but the error for exceeding file size is not.
$config ['upload_path'] = 'upload/Main_category_product/';
$path = $config ['upload_path'];
$config ['allowed_types'] = 'gif|jpg|jpeg|png';
$config ['max_size'] = '1024';
$config ['max_width'] = '1920';
$config ['max_height'] = '1280';
$this->load->library ( 'upload', $config );
foreach ( $_FILES as $key => $value ) {
if (! empty ( $value ['tmp_name'] ) && $value ['size'] > 0) {
if (! $this->upload->do_upload ( $key )) {
$errors = $this->upload->display_errors ();
flashMsg ( $errors );
} else {
// Code After Files Upload Success GOES HERE
}
}
}
Using the FlashMSG function send the messages right time to the users. OR collect all messages in a array and display in the end.

looping through multiple file upload indexes

I am trying to get the name and size index of all uploaded files but I can't get it work. it works like this:
foreach ($_FILES['file']['name'] as $key => $file){
echo $file;
}
but if I want to echo multiple indexes in the same loop, i tries this, but I get "undefined index 'name' and 'size'" warnings. What am I doing wrong? thanks
foreach ($_FILES['file'] as $key => $file){
echo $file['name'].
$file['size'];
}
<input name ="file[]" type = "file" multiple />
function handle_image_upload($frmFilesID = false, $thisFile = false) {
$tmpName = $_FILES["$frmFilesID"]['tmp_name'][$thisFile];
if (!is_uploaded_file($tmpName)) { return false; }
$fileName = $_FILES["$frmFilesID"]['name'][$thisFile];
$fileSize = $_FILES["$frmFilesID"]['size'][$thisFile];
$fileType = $_FILES["$frmFilesID"]['type'][$thisFile];
...

Codeigniter 2.1 - image name is not working properly on upload

I am using this function to upload images, and it is working except in one part. Where there are more then one image for upload, all images get their name from the first image (overwrite is set to off, so CI is adding number at the end of the name). How can I solve this problem?
function img_upload($folder) {
$this->path = './public/img/' . $folder;
$imgs = array();
$count = 0;
foreach($_FILES as $key => $value):
$img_name = is_array($value['name']) ? $value['name'][$count] : $value['name'];
$img_name = $this->char_replace($img_name, '_');
$count++;
$config = array(
'allowed_types' => 'jpg|jpeg|png|gif',
'upload_path' => $this->path,
'file_name' => $img_name
);
$this->CI->load->library('image_lib');
$this->CI->image_lib->clear();
$this->CI->load->library('upload', $config);
if($key != 'logo'):
if (!$this->CI->upload->do_upload($key)) {
} else {
$image = $this->CI->upload->data();
$imgs[] = $image['file_name'];
}
endif;
endforeach;
if(empty($imgs)):
return FALSE;
else:
return implode(',', $imgs);
endif;
}
Function char_replace is working without a problem.
function char_replace($text, $rep_simbol = " ")
{
$char = array('!', '&', '?', '/', '/\/', ':', ';', '#', '<', '>', '=', '^', '#', '~', '`', '[', ']', '{', '}');
return $name = str_replace($char, $rep_simbol, $text);
}
$this->CI->upload->do_upload($key) expects $_FILES['key'] to only contain one file.
What you can do is, make a copy of $_FILES, loop through it, and for each file set the values of $_FILES['key'].
function img_upload($folder) {
$this->path = './public/img/' . $folder;
$imgs = array();
// Copy of $_FILES
$thisFiles = $_FILES;
// Loop through copy of $_FILES
foreach($theFiles as $key => &$value){
// Create the $_FILES array for each individual file,
// so that do_upload can read it correctly
if(!is_array($value['name'])){
// If it's not an array, make it one,
// this will make our future code easier
foreach($value as $kv => &$val){
$val = array($val);
}
}
// Loop through each file and upload each one
foreach($value['name'] as $count=>$img_name){
$img_name = $this->char_replace($img_name, '_');
foreach($_FILES[$key] as $k => &$v){
// CodeIgniter will think this is the $_FILES array
$v = $theFiles[$key][$k][$count];
}
$config = array(
'allowed_types' => 'jpg|jpeg|png|gif',
'upload_path' => $this->path,
'file_name' => $img_name
);
$this->CI->load->library('image_lib');
$this->CI->image_lib->clear();
$this->CI->load->library('upload', $config);
if($key != 'logo'){
if (!$this->CI->upload->do_upload($key)) {
}
else {
$image = $this->CI->upload->data();
$imgs[] = $image['file_name'];
}
}
}
}
return !empty($imgs) ? implode(',', $imgs) : FALSE;
}
NOTE: This is untested.

Categories