from my below code i am trying to upload 4 images, but i am only able to upload last image to my upload folder.
My image validation and all the other task is working fine. But only i have problem with the multiple images to upload into its distinction folder.
Please check my below code and help to solve my problem.
MyController.php
class Booksetups extends CI_Controller {
public function __construct()
{
parent:: __construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library('session');
$this->load->model('Booksmodel');
$this->load->library('form_validation');
$this->load->library('pagination');
}
public function valid_upload()
{
$this->load->library('upload');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 2048;
$config['max_width'] = 385;
$config['max_height'] = 410;
$this->upload->initialize($config);
if (!$this->upload->validate_upload('img1') || !$this->upload->validate_upload('img2') || !$this->upload->validate_upload('img3') || !$this->upload->validate_upload('img4') ) {
$this->form_validation->set_message('valid_upload', $this->upload->display_errors());
return FALSE;
} else {
return TRUE;
}
}
function book($book_id = 0)
{
$config = array();
$config['base_url'] = 'http://localhost/thebestbookfinder.com/Booksetups/book/pgn/';
$config["total_rows"] = $this->Booksmodel->record_count();
$config['uri_segment'] = 4;
$config['per_page'] = 17;
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$this->form_validation->set_error_delimiters('<div class="error">', '</div>')->set_rules('book_title', '"Title"','trim|required|min_length[4]|max_length[150]|xss_clean');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>')->set_rules('edition_id', '"Edition Name"','trim|min_length[1]|max_length[150]|xss_clean');
//---------------------validating images---------------------------
$this->form_validation->set_rules('img1', 'Image 1', 'trim|xss_clean|callback_valid_upload');
$this->form_validation->set_rules('img2', 'Image 2', 'trim|xss_clean|callback_valid_upload');
$this->form_validation->set_rules('img3', 'Image 3', 'trim|xss_clean|callback_valid_upload');
$this->form_validation->set_rules('img4', 'Image 4', 'trim|xss_clean|callback_valid_upload');
//-----------Here i am uploading my images into my specified folder-------------------------------
if ($this->form_validation->run() === TRUE) {
$this->upload->do_upload('img1');
$this->upload->do_upload('img2');
$this->upload->do_upload('img3');
$this->upload->do_upload('img4');
$this->Booksmodel->entry_insert();
$this->session->set_flashdata('msg', '1 row(s) inserted.');
redirect(current_url());
}
................
................
My_Upload.php
Class My_Upload extends CI_Upload
{
public function __construct(){
parent::__construct();
}
public function validate_upload($field = 'img1')
{
// Is $_FILES[$field] set? If not, no reason to continue.
if (! isset($_FILES[$field])) {
$this->set_error('upload_no_file_selected');
return FALSE;
}
// Is the upload path valid?
if (! $this->validate_upload_path()) {
// errors will already be set by validate_upload_path() so just return FALSE
return FALSE;
}
// Was the file able to be uploaded? If not, determine the reason why.
if (! is_uploaded_file($_FILES[$field]['tmp_name'])) {
$error = ( ! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error'];
switch ($error) {
case 1:
// UPLOAD_ERR_INI_SIZE
$this->set_error('upload_file_exceeds_limit');
break;
case 2:
// UPLOAD_ERR_FORM_SIZE
$this->set_error('upload_file_exceeds_form_limit');
break;
case 3:
// UPLOAD_ERR_PARTIAL
$this->set_error('upload_file_partial');
break;
case 4:
// UPLOAD_ERR_NO_FILE
$this->set_error('upload_no_file_selected');
break;
case 6:
// UPLOAD_ERR_NO_TMP_DIR
$this->set_error('upload_no_temp_directory');
break;
case 7:
// UPLOAD_ERR_CANT_WRITE
$this->set_error('upload_unable_to_write_file');
break;
case 8:
// UPLOAD_ERR_EXTENSION
$this->set_error('upload_stopped_by_extension');
break;
default : $this->set_error('upload_no_file_selected');
break;
}
return FALSE;
}
// Set the uploaded data as class variables
$this->file_temp = $_FILES[$field]['tmp_name'];
$this->file_size = $_FILES[$field]['size'];
$this->_file_mime_type($_FILES[$field]);
$this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $this->file_type);
$this->file_type = strtolower(trim(stripslashes($this->file_type), '"'));
$this->file_name = $this->_prep_filename($_FILES[$field]['name']);
$this->file_ext = $this->get_extension($this->file_name);
$this->client_name = $this->file_name;
// Is the file type allowed to be uploaded?
if (! $this->is_allowed_filetype()) {
$this->set_error('upload_invalid_filetype');
return FALSE;
}
// if we're overriding, let's now make sure the new name and type is allowed
if ($this->_file_name_override != '') {
$this->file_name = $this->_prep_filename($this->_file_name_override);
// If no extension was provided in the file_name config item, use the uploaded one
if (strpos($this->_file_name_override, '.') === FALSE) {
$this->file_name .= $this->file_ext;
}
// An extension was provided, lets have it!
else
{
$this->file_ext = $this->get_extension($this->_file_name_override);
}
if (! $this->is_allowed_filetype(TRUE)) {
$this->set_error('upload_invalid_filetype');
return FALSE;
}
}
// Convert the file size to kilobytes
if ($this->file_size > 0) {
$this->file_size = round($this->file_size/1024, 2);
}
// Is the file size within the allowed maximum?
if (! $this->is_allowed_filesize()) {
$this->set_error('upload_invalid_filesize');
return FALSE;
}
// Are the image dimensions within the allowed size?
// Note: This can fail if the server has an open_basdir restriction.
if (! $this->is_allowed_dimensions()) {
$this->set_error('upload_invalid_dimensions');
return FALSE;
}
// Sanitize the file name for security
$this->file_name = $this->clean_file_name($this->file_name);
// Truncate the file name if it's too long
if ($this->max_filename > 0) {
$this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename);
}
// Remove white spaces in the name
if ($this->remove_spaces == TRUE) {
$this->file_name = preg_replace("/\s+/", "_", $this->file_name);
}
/*
* Validate the file name
* This function appends an number onto the end of
* the file if one with the same name already exists.
* If it returns false there was a problem.
*/
$this->orig_name = $this->file_name;
if ($this->overwrite == FALSE) {
$this->file_name = $this->set_filename($this->upload_path, $this->file_name);
if ($this->file_name === FALSE) {
return FALSE;
}
}
/*
* Run the file through the XSS hacking filter
* This helps prevent malicious code from being
* embedded within a file. Scripts can easily
* be disguised as images or other file types.
*/
if ($this->xss_clean) {
if ($this->do_xss_clean() === FALSE) {
$this->set_error('upload_unable_to_write_file');
return FALSE;
}
}
$this->set_image_properties($this->upload_path.$this->file_name);
return TRUE;
}
public function do_upload($field = 'img1')
{
/*
* Move the file to the final destination
* To deal with different server configurations
* we'll attempt to use copy() first. If that fails
* we'll use move_uploaded_file(). One of the two should
* reliably work in most environments
*/
if (! #copy($this->file_temp, $this->upload_path.$this->file_name)) {
if (! #move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name)) {
$this->set_error('upload_destination_error');
return FALSE;
}
}
/*
* Set the finalized image dimensions
* This sets the image width/height (assuming the
* file was an image). We use this information
* in the "data" function.
*/
return TRUE;
}
}
MyViewForm.php
<?php echo form_open_multipart('Booksetups/book');?>
<?php echo form_hidden('book_id',$fbook_id['value']);?>
<input type="file" name="img1" />
<input type="file" name="img2" />
<input type="file" name="img3" />
<input type="file" name="img4" />
<?php
echo form_submit($submitbtn);
echo form_reset($resetbtn);
?>
<?php echo form_close();?>
Use uploadify jquery plugin.Its easy to use and fully customized with real time progress bar and many more features.
Uploadify demo
Debug your do_upload function, you are not using local variable $ field anywhere
Related
I am working on a project and so I am writing Object Oriented PHP. Hence, I have created a class called FileUploader. This class has all the method to validate file size, and file extension type as well as create directories if not existing.
Everything works just fine but I noticed that it only creates empty directories and does not move the uploaded files. I tried accessing the File error form the stored property but it always gives 0 as the error code
This is the FileUploader class
<?php
namespace Utility\Classes;
class FileUploader
{
//property declarations
protected $error_msg = array();
protected $tmp_file_name;
protected $max_file_size;
protected $target_location;
protected $allowed_file_type = array();
protected $File;
protected $default_file_name = true;
private $backlink_step;
private $unit_size; //to keep track of measurement unit of upload sizes MB|KB|BYTES
function __construct(array $file, array $allowed_ext = [], int $file_max_size = 5)
{
$this->File = $file;
$this->backlink_step = '';
$this->set_allowed_extensions($allowed_ext);
$this->set_max_upload_size($file_max_size);
}
/*This method helps to make sure that files are uploaded to the exact location as desired
*as in the case of deep nesting of subdirectory process
*/
function set_backlink_step($prfx)
{
$this->backlink_step = $prfx;
}
function set_target(string $target, $dated = false)
{
$this->target_location = $target;
if ($dated) {
$this->target_location .= "/" . $date = date("M-Y");
}
}
function get_target()
{
return $this->target_location;
}
//method to set valid/allowed file types
function set_allowed_extensions(array $allowed_ext)
{
$this->allowed_file_type = $allowed_ext;
}
//method to get the allowed file extensions
function get_allowed_extensions()
{
return $this->allowed_file_type;
}
function set_error_msg($err)
{
$this->error_msg[] = $err;
}
function get_error_msg()
{
return $this->error_msg;
}
function set_file_name($name)
{
$this->File['name'] = $name;
}
function get_file_name()
{
return $this->File['name'];
}
function get_tmp_name()
{
return $this->File['tmp_name'];
}
/**
* #description: method to return file size in a specified unit
* #param:String ['TB'|'MB'|'KB'|'B'] default MB
* #return: Int file size
* */
function get_file_size(String $unit = "MB")
{
if (strtolower($unit) === "tb") {
$quadrant = 1024 * 1024 * 1024;
} elseif (strtolower($unit) === "mb") {
$quadrant = 1024 * 1024;
} elseif (strtolower($unit) === "kb") {
$quadrant = 1024;
} elseif (strtolower($unit) === "b") {
$quadrant = 1;
}
$size = $this->file_size() / $quadrant;
return number_format($size, 2);
}
/**
* #return int size of the file
* */
function file_size()
{
$fsize = $this->File['size'];
return $fsize;
}
/* Method to get the extension name of a file eg: jpg,mp4 */
function get_ext()
{
$extension = explode('.', $this->get_file_name());
return "." . end($extension);
}
function validate($allowed_ext = [])
{
//fall back to the object allowed_file_type property if param not set by user
if (empty($allowed_ext)) {
$allowed_ext = $this->get_allowed_extensions();
}
//validate allowed file type if specified in the array
if (!empty($allowed_ext)) {
if (!$this->is_allowed_extension($allowed_ext)) {
$this->set_error_msg("Type of '{$this->get_file_name()} does not match allowed file types [" . implode('|', $this->get_allowed_extensions()) . "]");
return false;
}
}
//validate file size
if ($this->is_above_max_upload_size()) {
$this->set_error_msg("Size of the file '{$this->get_file_name()}' is larger than max allowed size of {$this->get_max_upload_size()}");
return false;
}
return true;
}
/*Method to upload file
* #return: the uploaded target location
*/
function upload_file()
{
//create necessary directories if not in existence
$this->create_dir();
$target = $this->backlink_step . $this->target_location . "/" . $this->get_file_name();
//attempt upload of the file
if (move_uploaded_file($this->tmp_file_name, $target)) {
//update target location with the filename
return $target;
} else {
//return false;
die("tmp_name: {$this->get_tmp_name()} \n target: {$target} \n Error: {$this->File['error']}");
}
}
/*This method sets the maximum upload size for file track and album_art respectively
*This method ignores invalid value for unit and replaces it with bytes*/
function set_max_upload_size($file_size, $unit = "MB")
{
$mulitplicant = 1;
if (strtolower($unit) === "tb") {
$multiplicant = 1024 * 1024 * 1024;
} elseif (strtolower($unit) === "mb") {
$multiplicant = 1024 * 1024;
} elseif (strtolower($unit) === "kb") {
$multiplicant = 1024;
} else {
$unit = "Bytes";
}
$this->max_file_size = $multiplicant * $file_size; //set max size for file
$this->unit_size = strtoupper($unit);
}
function get_max_upload_size()
{
return $this->max_file_size;
}
/*Method to compare the size of files to be uploaded with the maximum allowed size*/
function is_above_max_upload_size()
{
$file_unit = $this->unit_size;
//return FALSE if upload size > max size otherwise TRUE
return ($this->file_size() > $this->get_max_upload_size()) ? true : false;
}
/*Method to check if upload file is allowed in by extension name
*The first paramater takes the string of the actual file extension
*The second parameter takes an array of allowed extensions
*/
function is_allowed_extension(array $allowed_ext)
{
return (!in_array($this->get_ext(), $allowed_ext)) ? false : true;
}
//method to create directories
function create_dir()
{
//check if user set a storage location and attempt to create the location
if (empty($this->get_target())) {
$this->set_error_msg('Target Not set.');
return false;
}
//Create the directory
$location = explode('/', $this->get_target());
$prepend = $this->backlink_step . "";
foreach ($location as $key => $value) {
if (!is_dir($prepend . $value)) {
mkdir($prepend . $value);
}
$prepend .= $value . "/";
}
}
}
Then I have another php script where I process the uploaded file by instantiating the FileUploader Class with the $_FILES variable process.php
require_once "../vendor/autoload.php";
use Utility\Classes\FileUploader;
//Instantiate new FileUploader with the files to be uploaded.
$LogoUploader = new FileUploader($_FILES['logo'], ['.png', '.jpg']);
//validate logo size and type - Upload to folder if everything Ok
$logo_validated = $LogoUploader->validate();
//upload files that passed validation
if ($logo_validated) {
$LogoUploader->set_target($location);
$LogoUploader->set_backlink_step('../');
$ltarget = $LogoUploader->upload_file();
if (!$ltarget) {
//upload error
print_error($LogoUploader->get_error_msg());
exit;
} else { //upload success
print "Logo uploaded successfully";
}
} else { //validation error
print_error($LogoUploader->get_error_msg());
exit;
}
Please what am I not doing right?? everything is ok, validation is working, user can set the upload target and if it does not exist, it will be created but it does not upload the file into the created directory or anywhere else in my working directory
I think you need to change the following line
if (move_uploaded_file($this->tmp_file_name, $target)) {
to
if (move_uploaded_file( $this->get_tmp_name(), $target )) {
in the upload_file method. ie:
public function upload_file(){
$this->create_dir();
$target = $this->backlink_step . $this->target_location . "/" . $this->get_file_name();
if (move_uploaded_file( $this->get_tmp_name(), $target )) {
return $target;
} else {
die("tmp_name: {$this->get_tmp_name()} \n target: {$target} \n Error: {$this->File['error']}");
}
}
I'm trying to build some application but have frustated in uploded code with ci, I used multi_upload.
I won upload some file and send them with email, but on CI file_path must be uploaded in server root so I try uploaded and find the file_path.
Here is my controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Upload extends CI_Controller {
function index()
{
$this->load->view('upload_form');
}
function do_upload()
{
$config['upload_path'] = './uploads/'; // server directory
$config['allowed_types'] = 'gif|jpg|png'; // by extension, will check for whether it is an image
$config['max_size'] = '1000'; // in kb
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->load->library('Multi_upload');
$files = $this->multi_upload->go_upload();
if ( $files )
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array(
'upload_data' =>$this->upload->data()
);
$this->load->view('upload_success', $data);
}
}
}
?>
my upload_form:
<?php if (isset($error)) echo $error;?>
<form action="http://localhost/hemmmm/index.php/upload/do_upload" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<input type="file" name="userfile[]" size="20" class="multi"
data-ajax="false"><br /><br />
<input type="submit" value="upload" />
My succes_form:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('upload', 'Upload More Files!'); ?></p>
</body>
</html>
my multi_upload library :
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* This library assumes that you have already loaded the default CI Upload Library seperately
*
* Functions is based upon CI_Upload, Feel free to modify this
* library to function as an extension to CI_Upload
*
* Library modified by: Alvin Mites
* http://www.mitesdesign.com
*
*/
class Multi_upload {
function Multi_upload () {
// $CI =& get_instance();
}
/**
* Perform multiple file uploads
* Based upon JQuery Multiple Upload Class
* see http://www.fyneworks.com/jquery/multiple-file-upload/
*/
function go_upload($field = 'userfile') {
$CI =& get_instance();
// Is $_FILES[$field] set? If not, no reason to continue.
if ( ! isset($_FILES[$field]['name'][0]))
{
$CI->upload->set_error('upload_no_file_selected');
return FALSE;
} else
{
$num_files = count($_FILES[$field]['name']) -1;
$file_list = array();
$error_hold = array();
$error_upload = FALSE;
}
// Is the upload path valid?
if ( ! $CI->upload->validate_upload_path())
{
// errors will already be set by validate_upload_path() so just return FALSE
return FALSE;
}
for ($i=0; $i < $num_files; $i++) {
// $fname = $_FILES[$field]['name'][$i];
// echo "$fname\n\n<br><br>\n\n";
$error_hold[$i] = FALSE;
// Was the file able to be uploaded? If not, determine the reason why.
if ( ! is_uploaded_file($_FILES[$field]['tmp_name'][$i]))
{
$error = ( ! isset($_FILES[$field]['error'][$i])) ? 4 : $_FILES[$field]['error'][$i];
switch($error)
{
case 1: // UPLOAD_ERR_INI_SIZE
$error_hold[$i] = 'upload_file_exceeds_limit';
break;
case 2: // UPLOAD_ERR_FORM_SIZE
$error_hold[$i] = 'upload_file_exceeds_form_limit';
break;
case 3: // UPLOAD_ERR_PARTIAL
$error_hold[$i] = 'upload_file_partial';
break;
case 4: // UPLOAD_ERR_NO_FILE
$error_hold[$i] = 'upload_no_file_selected';
break;
case 6: // UPLOAD_ERR_NO_TMP_DIR
$error_hold[$i] = 'upload_no_temp_directory';
break;
case 7: // UPLOAD_ERR_CANT_WRITE
$error_hold[$i] = 'upload_unable_to_write_file';
break;
case 8: // UPLOAD_ERR_EXTENSION
$error_hold[$i] = 'upload_stopped_by_extension';
break;
default :
$error_hold[$i] = 'upload_no_file_selected';
break;
}
return FALSE;
}
// Set the uploaded data as class variables
$CI->upload->file_temp = $_FILES[$field]['tmp_name'][$i];
$CI->upload->file_name = $this->_prep_filename($_FILES[$field]['name'][$i]);
$CI->upload->file_size = $_FILES[$field]['size'][$i];
$CI->upload->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type'][$i]);
$CI->upload->file_type = strtolower($CI->upload->file_type);
$CI->upload->file_ext = $CI->upload->get_extension($_FILES[$field]['name'][$i]);
// Convert the file size to kilobytes
if ($CI->upload->file_size > 0)
{
$CI->upload->file_size = round($CI->upload->file_size/1024, 2);
}
// Is the file type allowed to be uploaded?
if ( ! $CI->upload->is_allowed_filetype())
{
$error_hold[$i] = 'upload_invalid_filetype';
}
// Is the file size within the allowed maximum?
if ( ! $CI->upload->is_allowed_filesize())
{
$error_hold[$i] = 'upload_invalid_filesize';
}
// Are the image dimensions within the allowed size?
// Note: This can fail if the server has an open_basdir restriction.
if ( ! $CI->upload->is_allowed_dimensions())
{
$error_hold[$i] = 'upload_invalid_dimensions';
}
// Sanitize the file name for security
$CI->upload->file_name = $CI->upload->clean_file_name($CI->upload->file_name);
// Remove white spaces in the name
if ($CI->upload->remove_spaces == TRUE)
{
$CI->upload->file_name = preg_replace("/\s+/", "_", $CI->upload->file_name);
}
/*
* Validate the file name
* This function appends an number onto the end of
* the file if one with the same name already exists.
* If it returns false there was a problem.
*/
$CI->upload->orig_name = $CI->upload->file_name;
if ($CI->upload->overwrite == FALSE)
{
$CI->upload->file_name = $CI->upload->set_filename($CI->upload->upload_path, $CI->upload->file_name);
if ($CI->upload->file_name === FALSE)
{
$error_hold[$i] = TRUE;
}
}
/*
* Move the file to the final destination
* To deal with different server configurations
* we'll attempt to use copy() first. If that fails
* we'll use move_uploaded_file(). One of the two should
* reliably work in most environments
*/
if ( ! #copy($CI->upload->file_temp, $CI->upload->upload_path.$CI->upload->file_name))
{
if ( ! #move_uploaded_file($CI->upload->file_temp, $CI->upload->upload_path.$CI->upload->file_name))
{
$error_hold[$i] = 'upload_destination_error';
}
}
/*
* Run the file through the XSS hacking filter
* This helps prevent malicious code from being
* embedded within a file. Scripts can easily
* be disguised as images or other file types.
*/
if ($CI->upload->xss_clean == TRUE)
{
$CI->upload->do_xss_clean();
}
if ($error_hold[$i]) {
$error_upload = TRUE;
// echo $error_hold[$i];
} else {
if ($imageVar = $this->multiple_image_properties($CI->upload->upload_path.$CI->upload->file_name)) {
$file_list[] = array(
'name' => $CI->upload->file_name,
'file' => $CI->upload->upload_path.$CI->upload->file_name,
'size' => $CI->upload->file_size,
'ext' => $CI->upload->file_ext,
'image_type' => $imageVar->image_type,
'height' => $imageVar->height,
'width' => $imageVar->width
);
} else {
$file_list[] = array(
'name' => $CI->upload->file_name,
'file' => $CI->upload->upload_path.$CI->upload->file_name,
'size' => $CI->upload->file_size,
'type' => $CI->upload->file_type,
'ext' => $CI->upload->file_ext,
);
}
}
// For debugging
/*
if (strlen($error_hold[$i]) > 1) {
print_r($error_hold);
}
*/
} // end for loop
// Add error display for individual files
if ($error_upload) {
$this->set_error($error_hold);
return FALSE;
} else {
return $file_list;
}
}
// --------------------------------------------------------------------
/**
* Set Image Properties
*
* Uses GD to determine the width/height/type of image
*
* #access public
* #param string
* #return void
*/
function multiple_image_properties($path = '')
{
$CI =& get_instance();
if ( ! $CI->upload->is_image())
{
return false;
}
if (function_exists('getimagesize'))
{
if (FALSE !== ($D = #getimagesize($path)))
{
$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
$image->width = $D['0'];
$image->height = $D['1'];
$image->image_type = ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']];
return $image;
}
}
}
// --------------------------------------------------------------------
/**
* Set an error message
*
* #access public
* #param string
* #return void
*/
function set_error($msg)
{
$CI =& get_instance();
$CI->lang->load('upload');
if (is_array($msg))
{
foreach ($msg as $val)
{
$msg = ($CI->lang->line($val) == FALSE) ? $val : $CI->lang->line($val);
$this->error_msg[] = $msg;
log_message('error', $msg);
}
}
else
{
$msg = ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg);
$this->error_msg[] = $msg;
log_message('error', $msg);
}
}
// --------------------------------------------------------------------
protected function _prep_filename($filename) {
$CI = & get_instance();
if (strpos($filename, '.') === FALSE OR $CI->upload->allowed_types == '*') {
return $filename;
}
$parts = explode('.', $filename);
$ext = array_pop($parts);
$filename = array_shift($parts);
foreach ($parts as $part) {
if (!in_array(strtolower($part), $CI->upload->allowed_types) OR $CI->upload->mimes_types(strtolower($part)) === FALSE) {
$filename .= '.' . $part . '_';
} else {
$filename .= '.' . $part;
}
}
$filename .= '.' . $ext;
return $filename;
}
}
?>
When I try to upload one file it works and I have great explaination about upload_data
but when I try to upload multiple files it works the file is uploaded, but just displays
status about last file uploaded.
$file_list array is being overwritten every time it processes an image from the looks of it. Try incrementing that with the $i variable when it's being populated.
$file_list[$i] = array
How do I solve this error?
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: admin/tour.php
Line Number: 81
this is line 81:
$files = $this->multi_upload->go_upload();
var_dump($files);
$images = array();
foreach ($files as $img) { //line 81
$images[] = $img['file'];
}
this my $files in top code:
function go_upload($field = 'userfile') {
$CI =& get_instance();
// Is $_FILES[$field] set? If not, no reason to continue.
if ( ! isset($_FILES[$field]['name'][0]))
{
$CI->upload->set_error('upload_no_file_selected');
return FALSE;
} else
{
$num_files = count($_FILES[$field]['name']) -1;
$file_list = array();
$error_hold = array();
$error_upload = FALSE;
}
// Is the upload path valid?
if ( ! $CI->upload->validate_upload_path())
{
// errors will already be set by validate_upload_path() so just return FALSE
return FALSE;
}
for ($i=0; $i < $num_files; $i++) {
// $fname = $_FILES[$field]['name'][$i];
// echo "$fname\n\n<br><br>\n\n";
$error_hold[$i] = FALSE;
// Was the file able to be uploaded? If not, determine the reason why.
if ( ! is_uploaded_file($_FILES[$field]['tmp_name'][$i]))
{
$error = ( ! isset($_FILES[$field]['error'][$i])) ? 4 : $_FILES[$field]['error'][$i];
switch($error)
{
case 1: // UPLOAD_ERR_INI_SIZE
$error_hold[$i] = 'upload_file_exceeds_limit';
break;
case 2: // UPLOAD_ERR_FORM_SIZE
$error_hold[$i] = 'upload_file_exceeds_form_limit';
break;
case 3: // UPLOAD_ERR_PARTIAL
$error_hold[$i] = 'upload_file_partial';
break;
case 4: // UPLOAD_ERR_NO_FILE
$error_hold[$i] = 'upload_no_file_selected';
break;
case 6: // UPLOAD_ERR_NO_TMP_DIR
$error_hold[$i] = 'upload_no_temp_directory';
break;
case 7: // UPLOAD_ERR_CANT_WRITE
$error_hold[$i] = 'upload_unable_to_write_file';
break;
case 8: // UPLOAD_ERR_EXTENSION
$error_hold[$i] = 'upload_stopped_by_extension';
break;
default :
$error_hold[$i] = 'upload_no_file_selected';
break;
}
return FALSE;
}
// Set the uploaded data as class variables
$CI->upload->file_temp = $_FILES[$field]['tmp_name'][$i];
$CI->upload->file_name = $_FILES[$field]['name'][$i];
$CI->upload->file_size = $_FILES[$field]['size'][$i];
$CI->upload->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type'][$i]);
$CI->upload->file_type = strtolower($CI->upload->file_type);
$CI->upload->file_ext = $CI->upload->get_extension($_FILES[$field]['name'][$i]);
// Convert the file size to kilobytes
if ($CI->upload->file_size > 0)
{
$CI->upload->file_size = round($CI->upload->file_size/1024, 2);
}
// Is the file type allowed to be uploaded?
if ( ! $CI->upload->is_allowed_filetype())
{
$error_hold[$i] = 'upload_invalid_filetype';
}
// Is the file size within the allowed maximum?
if ( ! $CI->upload->is_allowed_filesize())
{
$error_hold[$i] = 'upload_invalid_filesize';
}
// Are the image dimensions within the allowed size?
// Note: This can fail if the server has an open_basdir restriction.
if ( ! $CI->upload->is_allowed_dimensions())
{
$error_hold[$i] = 'upload_invalid_dimensions';
}
// Sanitize the file name for security
$CI->upload->file_name = $CI->upload->clean_file_name($CI->upload->file_name);
// Remove white spaces in the name
if ($CI->upload->remove_spaces == TRUE)
{
$CI->upload->file_name = preg_replace("/\s+/", "_", $CI->upload->file_name);
}
/*
* Validate the file name
* This function appends an number onto the end of
* the file if one with the same name already exists.
* If it returns false there was a problem.
*/
$CI->upload->orig_name = $CI->upload->file_name;
if ($CI->upload->overwrite == FALSE)
{
$CI->upload->file_name = $CI->upload->set_filename($CI->upload->upload_path, $CI->upload->file_name);
if ($CI->upload->file_name === FALSE)
{
$error_hold[$i] = TRUE;
}
}
/*
* Move the file to the final destination
* To deal with different server configurations
* we'll attempt to use copy() first. If that fails
* we'll use move_uploaded_file(). One of the two should
* reliably work in most environments
*/
if ( ! #copy($CI->upload->file_temp, $CI->upload->upload_path.$CI->upload->file_name))
{
if ( ! #move_uploaded_file($CI->upload->file_temp, $CI->upload->upload_path.$CI->upload->file_name))
{
$error_hold[$i] = 'upload_destination_error';
}
}
/*
* Run the file through the XSS hacking filter
* This helps prevent malicious code from being
* embedded within a file. Scripts can easily
* be disguised as images or other file types.
*/
if ($CI->upload->xss_clean == TRUE)
{
$CI->upload->do_xss_clean();
}
if ($error_hold[$i]) {
$error_upload = TRUE;
// echo $error_hold[$i];
} else {
if ($imageVar = $this->multiple_image_properties($CI->upload->upload_path.$CI->upload->file_name)) {
$file_list[] = array(
'name' => $CI->upload->file_name,
'file' => $CI->upload->upload_path.$CI->upload->file_name,
'size' => $CI->upload->file_size,
'ext' => $CI->upload->file_ext,
'image_type' => $imageVar->image_type,
'height' => $imageVar->height,
'width' => $imageVar->width
);
} else {
$file_list[] = array(
'name' => $CI->upload->file_name,
'file' => $CI->upload->upload_path.$CI->upload->file_name,
'size' => $CI->upload->file_size,
'type' => $CI->upload->file_type,
'ext' => $CI->upload->file_ext,
);
}
}
// For debugging
/*
if (strlen($error_hold[$i]) > 1) {
print_r($error_hold);
}
*/
} // end for loop
// Add error display for individual files
if ($error_upload) {
$this->set_error($error_hold);
return FALSE;
} else {
return $file_list;
}
}
The simple answer is that $files is not an array. foreach only works on arrays. We don't know what the value is, but in any case, it's not right. You'd have to look at the go_upload function to see why it's not doing what you expect.
Actually doing like this you wil get the file or the value you want to.
foreach ($files as $img) { //line 81
echo $img; // echo the Var and you will see..
}
This line -> $files = $this->multi_upload->go_upload(); probably come from a file object in your form, right? Then it must to be named like this file[] and not only file. You need to be specific that it is an Array. Otherwise nothing will happen.
Too avoid seeing this warning message you should count the array:
if (count($files) > 0)
{
foreach ($files as $img) { //line 81
$images[] = $img['file'];
}
}
Regarding the 'Invalid argument supplied for foreach()' error this is probably because $files is not an array (or similar). The best way to do this IMHO is:
$files = $this->multi_upload->go_upload();
echo '<pre>';
echo "Files:\n";
print_r($files);
echo '</pre>';
$images = array();
foreach ($files as $img) { //this is line 80
$images[] = $img['file'];
}
if ( ! $files )
{
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('admin/tour/insert_foreign');
}
Please make this change and show us the output.
I figure I would just share how I handle multiple uploads in CI, it's a little different than your method:
Form looks like this:
<?php echo form_open_multipart('upload/multiple_upload');?>
<input type="file" name="userfile[]" size="20" /><br />
<input type="file" name="userfile[]" size="20" /><br />
</form>
Upload/multiple_upload function in controller looks like this:
function multiple_upload()
{
$config['upload_path'] = './userpics/originals/'; // server directory
$config['allowed_types'] = 'gif|jpg|png'; // by extension, will check for whether it is an image
$config['max_size'] = '512'; // in kb
//$config['max_width'] = '1024';
//$config['max_height'] = '768';
$this->load->library('myupload');
$error = array(); $data = array();
for ($i=0;$i<count($_FILES['userfile']['name']);$i++) {
$this->myupload->initialize($config);
if (!$this->myupload->do_upload('userfile',$i)) {
$error[] = $this->myupload->display_errors();
}
$data[$i] = $this->myupload->data(); //gradually build up upload->data()
}
if ( count($error) > 0 )
{
print_r($error);
}
else
{
print_r($data);
}
}
At this point I made a copy of CI upload class, and pasted it into my applications library directory. A few changes need to be made. I named it myupload.
# Line 143:
public function do_upload($field = 'userfile')
change to
public function do_upload($field = 'userfile', $i = 0)
Any lines in this function above line 200, you must add [$i] to the end of the $_FILES variables.
Example:
is_uploaded_file($_FILES[$field]['tmp_name'])
change to:
is_uploaded_file($_FILES[$field]['tmp_name'][$i])
There are 9 lines to be updated.
Are you sure that you get an array? is see several return FALSE. So you should check,
if ($files !== FALSE)
or casting it to an (empty) array (if false returns) with
$files = (array) $this->multi_upload->go_upload();
i have a error to use of multiupload with CodeIgniter:
What changes can, to be problem i solve?
waht do i do?
With respect
this is error:
Fatal error: Call to protected method CI_Upload::_prep_filename() from
context 'Multi_upload' in
D:\xampp\htdocs\CodeIgniter_2.0.0\application\libraries\Multi_upload.php
on line 91
this full my class, Line 91 is indicated:
class Multi_upload {
function Multi_upload () {
// $CI =& get_instance();
}
/**
* Perform multiple file uploads
* Based upon JQuery Multiple Upload Class
* see http://www.fyneworks.com/jquery/multiple-file-upload/
*/
function go_upload($field = 'userfile') {
$CI =& get_instance();
// Is $_FILES[$field] set? If not, no reason to continue.
if ( ! isset($_FILES[$field]['name'][0]))
{
$CI->upload->set_error('upload_no_file_selected');
return FALSE;
} else
{
$num_files = count($_FILES[$field]['name']) -1;
$file_list = array();
$error_hold = array();
$error_upload = FALSE;
}
// Is the upload path valid?
if ( ! $CI->upload->validate_upload_path())
{
// errors will already be set by validate_upload_path() so just return FALSE
return FALSE;
}
for ($i=0; $i < $num_files; $i++) {
// $fname = $_FILES[$field]['name'][$i];
// echo "$fname\n\n<br><br>\n\n";
$error_hold[$i] = FALSE;
// Was the file able to be uploaded? If not, determine the reason why.
if ( ! is_uploaded_file($_FILES[$field]['tmp_name'][$i]))
{
$error = ( ! isset($_FILES[$field]['error'][$i])) ? 4 : $_FILES[$field]['error'][$i];
switch($error)
{
case 1: // UPLOAD_ERR_INI_SIZE
$error_hold[$i] = 'upload_file_exceeds_limit';
break;
case 2: // UPLOAD_ERR_FORM_SIZE
$error_hold[$i] = 'upload_file_exceeds_form_limit';
break;
case 3: // UPLOAD_ERR_PARTIAL
$error_hold[$i] = 'upload_file_partial';
break;
case 4: // UPLOAD_ERR_NO_FILE
$error_hold[$i] = 'upload_no_file_selected';
break;
case 6: // UPLOAD_ERR_NO_TMP_DIR
$error_hold[$i] = 'upload_no_temp_directory';
break;
case 7: // UPLOAD_ERR_CANT_WRITE
$error_hold[$i] = 'upload_unable_to_write_file';
break;
case 8: // UPLOAD_ERR_EXTENSION
$error_hold[$i] = 'upload_stopped_by_extension';
break;
default :
$error_hold[$i] = 'upload_no_file_selected';
break;
}
return FALSE;
}
// Set the uploaded data as class variables
$CI->upload->file_temp = $_FILES[$field]['tmp_name'][$i];
////////////////////////////////////here - line 91/////////////////////////////////
$CI->upload->file_name = $CI->upload->_prep_filename($_FILES[$field]['name'][$i]); // this is line 91
//////////////////////////////////////////////////////////////////////////////////
$CI->upload->file_size = $_FILES[$field]['size'][$i];
$CI->upload->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type'][$i]);
$CI->upload->file_type = strtolower($CI->upload->file_type);
$CI->upload->file_ext = $CI->upload->get_extension($_FILES[$field]['name'][$i]);
// Convert the file size to kilobytes
if ($CI->upload->file_size > 0)
{
$CI->upload->file_size = round($CI->upload->file_size/1024, 2);
}
// Is the file type allowed to be uploaded?
if ( ! $CI->upload->is_allowed_filetype())
{
$error_hold[$i] = 'upload_invalid_filetype';
}
// Is the file size within the allowed maximum?
if ( ! $CI->upload->is_allowed_filesize())
{
$error_hold[$i] = 'upload_invalid_filesize';
}
// Are the image dimensions within the allowed size?
// Note: This can fail if the server has an open_basdir restriction.
if ( ! $CI->upload->is_allowed_dimensions())
{
$error_hold[$i] = 'upload_invalid_dimensions';
}
// Sanitize the file name for security
$CI->upload->file_name = $CI->upload->clean_file_name($CI->upload->file_name);
// Remove white spaces in the name
if ($CI->upload->remove_spaces == TRUE)
{
$CI->upload->file_name = preg_replace("/\s+/", "_", $CI->upload->file_name);
}
/*
* Validate the file name
* This function appends an number onto the end of
* the file if one with the same name already exists.
* If it returns false there was a problem.
*/
$CI->upload->orig_name = $CI->upload->file_name;
if ($CI->upload->overwrite == FALSE)
{
$CI->upload->file_name = $CI->upload->set_filename($CI->upload->upload_path, $CI->upload->file_name);
if ($CI->upload->file_name === FALSE)
{
$error_hold[$i] = TRUE;
}
}
/*
* Move the file to the final destination
* To deal with different server configurations
* we'll attempt to use copy() first. If that fails
* we'll use move_uploaded_file(). One of the two should
* reliably work in most environments
*/
if ( ! #copy($CI->upload->file_temp, $CI->upload->upload_path.$CI->upload->file_name))
{
if ( ! #move_uploaded_file($CI->upload->file_temp, $CI->upload->upload_path.$CI->upload->file_name))
{
$error_hold[$i] = 'upload_destination_error';
}
}
/*
* Run the file through the XSS hacking filter
* This helps prevent malicious code from being
* embedded within a file. Scripts can easily
* be disguised as images or other file types.
*/
if ($CI->upload->xss_clean == TRUE)
{
$CI->upload->do_xss_clean();
}
if ($error_hold[$i]) {
$error_upload = TRUE;
// echo $error_hold[$i];
} else {
if ($imageVar = $this->multiple_image_properties($CI->upload->upload_path.$CI->upload->file_name)) {
$file_list[] = array(
'name' => $CI->upload->file_name,
'file' => $CI->upload->upload_path.$CI->upload->file_name,
'size' => $CI->upload->file_size,
'ext' => $CI->upload->file_ext,
'image_type' => $imageVar->image_type,
'height' => $imageVar->height,
'width' => $imageVar->width
);
} else {
$file_list[] = array(
'name' => $CI->upload->file_name,
'file' => $CI->upload->upload_path.$CI->upload->file_name,
'size' => $CI->upload->file_size,
'type' => $CI->upload->file_type,
'ext' => $CI->upload->file_ext,
);
}
}
// For debugging
/*
if (strlen($error_hold[$i]) > 1) {
print_r($error_hold);
}
*/
} // end for loop
// Add error display for individual files
if ($error_upload) {
$this->set_error($error_hold);
return FALSE;
} else {
return $file_list;
}
}
// --------------------------------------------------------------------
/**
* Set Image Properties
*
* Uses GD to determine the width/height/type of image
*
* #access public
* #param string
* #return void
*/
function multiple_image_properties($path = '')
{
$CI =& get_instance();
if ( ! $CI->upload->is_image())
{
return false;
}
if (function_exists('getimagesize'))
{
if (FALSE !== ($D = #getimagesize($path)))
{
$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
$image->width = $D['0'];
$image->height = $D['1'];
$image->image_type = ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']];
return $image;
}
}
}
// --------------------------------------------------------------------
/**
* Set an error message
*
* #access public
* #param string
* #return void
*/
function set_error($msg)
{
$CI =& get_instance();
$CI->lang->load('upload');
if (is_array($msg))
{
foreach ($msg as $val)
{
$msg = ($CI->lang->line($val) == FALSE) ? $val : $CI->lang->line($val);
$this->error_msg[] = $msg;
log_message('error', $msg);
}
}
else
{
$msg = ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg);
$this->error_msg[] = $msg;
log_message('error', $msg);
}
}
// --------------------------------------------------------------------
}
?>
I read the library and I think this may help. You must replace the line 91 with this:
$CI->upload->file_name = $_FILES[$field]['name'][$i];
I hope you find it useful.
CI_Upload::_prep_filename() is a protected method. You cannot call it directly outside of the class.
How do I solve this error?
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: admin/tour.php
Line Number: 81
this is line 81:
$files = $this->multi_upload->go_upload();
var_dump($files);
$images = array();
foreach ($files as $img) { //line 81
$images[] = $img['file'];
}
this my $files in top code:
function go_upload($field = 'userfile') {
$CI =& get_instance();
// Is $_FILES[$field] set? If not, no reason to continue.
if ( ! isset($_FILES[$field]['name'][0]))
{
$CI->upload->set_error('upload_no_file_selected');
return FALSE;
} else
{
$num_files = count($_FILES[$field]['name']) -1;
$file_list = array();
$error_hold = array();
$error_upload = FALSE;
}
// Is the upload path valid?
if ( ! $CI->upload->validate_upload_path())
{
// errors will already be set by validate_upload_path() so just return FALSE
return FALSE;
}
for ($i=0; $i < $num_files; $i++) {
// $fname = $_FILES[$field]['name'][$i];
// echo "$fname\n\n<br><br>\n\n";
$error_hold[$i] = FALSE;
// Was the file able to be uploaded? If not, determine the reason why.
if ( ! is_uploaded_file($_FILES[$field]['tmp_name'][$i]))
{
$error = ( ! isset($_FILES[$field]['error'][$i])) ? 4 : $_FILES[$field]['error'][$i];
switch($error)
{
case 1: // UPLOAD_ERR_INI_SIZE
$error_hold[$i] = 'upload_file_exceeds_limit';
break;
case 2: // UPLOAD_ERR_FORM_SIZE
$error_hold[$i] = 'upload_file_exceeds_form_limit';
break;
case 3: // UPLOAD_ERR_PARTIAL
$error_hold[$i] = 'upload_file_partial';
break;
case 4: // UPLOAD_ERR_NO_FILE
$error_hold[$i] = 'upload_no_file_selected';
break;
case 6: // UPLOAD_ERR_NO_TMP_DIR
$error_hold[$i] = 'upload_no_temp_directory';
break;
case 7: // UPLOAD_ERR_CANT_WRITE
$error_hold[$i] = 'upload_unable_to_write_file';
break;
case 8: // UPLOAD_ERR_EXTENSION
$error_hold[$i] = 'upload_stopped_by_extension';
break;
default :
$error_hold[$i] = 'upload_no_file_selected';
break;
}
return FALSE;
}
// Set the uploaded data as class variables
$CI->upload->file_temp = $_FILES[$field]['tmp_name'][$i];
$CI->upload->file_name = $_FILES[$field]['name'][$i];
$CI->upload->file_size = $_FILES[$field]['size'][$i];
$CI->upload->file_type = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type'][$i]);
$CI->upload->file_type = strtolower($CI->upload->file_type);
$CI->upload->file_ext = $CI->upload->get_extension($_FILES[$field]['name'][$i]);
// Convert the file size to kilobytes
if ($CI->upload->file_size > 0)
{
$CI->upload->file_size = round($CI->upload->file_size/1024, 2);
}
// Is the file type allowed to be uploaded?
if ( ! $CI->upload->is_allowed_filetype())
{
$error_hold[$i] = 'upload_invalid_filetype';
}
// Is the file size within the allowed maximum?
if ( ! $CI->upload->is_allowed_filesize())
{
$error_hold[$i] = 'upload_invalid_filesize';
}
// Are the image dimensions within the allowed size?
// Note: This can fail if the server has an open_basdir restriction.
if ( ! $CI->upload->is_allowed_dimensions())
{
$error_hold[$i] = 'upload_invalid_dimensions';
}
// Sanitize the file name for security
$CI->upload->file_name = $CI->upload->clean_file_name($CI->upload->file_name);
// Remove white spaces in the name
if ($CI->upload->remove_spaces == TRUE)
{
$CI->upload->file_name = preg_replace("/\s+/", "_", $CI->upload->file_name);
}
/*
* Validate the file name
* This function appends an number onto the end of
* the file if one with the same name already exists.
* If it returns false there was a problem.
*/
$CI->upload->orig_name = $CI->upload->file_name;
if ($CI->upload->overwrite == FALSE)
{
$CI->upload->file_name = $CI->upload->set_filename($CI->upload->upload_path, $CI->upload->file_name);
if ($CI->upload->file_name === FALSE)
{
$error_hold[$i] = TRUE;
}
}
/*
* Move the file to the final destination
* To deal with different server configurations
* we'll attempt to use copy() first. If that fails
* we'll use move_uploaded_file(). One of the two should
* reliably work in most environments
*/
if ( ! #copy($CI->upload->file_temp, $CI->upload->upload_path.$CI->upload->file_name))
{
if ( ! #move_uploaded_file($CI->upload->file_temp, $CI->upload->upload_path.$CI->upload->file_name))
{
$error_hold[$i] = 'upload_destination_error';
}
}
/*
* Run the file through the XSS hacking filter
* This helps prevent malicious code from being
* embedded within a file. Scripts can easily
* be disguised as images or other file types.
*/
if ($CI->upload->xss_clean == TRUE)
{
$CI->upload->do_xss_clean();
}
if ($error_hold[$i]) {
$error_upload = TRUE;
// echo $error_hold[$i];
} else {
if ($imageVar = $this->multiple_image_properties($CI->upload->upload_path.$CI->upload->file_name)) {
$file_list[] = array(
'name' => $CI->upload->file_name,
'file' => $CI->upload->upload_path.$CI->upload->file_name,
'size' => $CI->upload->file_size,
'ext' => $CI->upload->file_ext,
'image_type' => $imageVar->image_type,
'height' => $imageVar->height,
'width' => $imageVar->width
);
} else {
$file_list[] = array(
'name' => $CI->upload->file_name,
'file' => $CI->upload->upload_path.$CI->upload->file_name,
'size' => $CI->upload->file_size,
'type' => $CI->upload->file_type,
'ext' => $CI->upload->file_ext,
);
}
}
// For debugging
/*
if (strlen($error_hold[$i]) > 1) {
print_r($error_hold);
}
*/
} // end for loop
// Add error display for individual files
if ($error_upload) {
$this->set_error($error_hold);
return FALSE;
} else {
return $file_list;
}
}
The simple answer is that $files is not an array. foreach only works on arrays. We don't know what the value is, but in any case, it's not right. You'd have to look at the go_upload function to see why it's not doing what you expect.
Actually doing like this you wil get the file or the value you want to.
foreach ($files as $img) { //line 81
echo $img; // echo the Var and you will see..
}
This line -> $files = $this->multi_upload->go_upload(); probably come from a file object in your form, right? Then it must to be named like this file[] and not only file. You need to be specific that it is an Array. Otherwise nothing will happen.
Too avoid seeing this warning message you should count the array:
if (count($files) > 0)
{
foreach ($files as $img) { //line 81
$images[] = $img['file'];
}
}
Regarding the 'Invalid argument supplied for foreach()' error this is probably because $files is not an array (or similar). The best way to do this IMHO is:
$files = $this->multi_upload->go_upload();
echo '<pre>';
echo "Files:\n";
print_r($files);
echo '</pre>';
$images = array();
foreach ($files as $img) { //this is line 80
$images[] = $img['file'];
}
if ( ! $files )
{
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('admin/tour/insert_foreign');
}
Please make this change and show us the output.
I figure I would just share how I handle multiple uploads in CI, it's a little different than your method:
Form looks like this:
<?php echo form_open_multipart('upload/multiple_upload');?>
<input type="file" name="userfile[]" size="20" /><br />
<input type="file" name="userfile[]" size="20" /><br />
</form>
Upload/multiple_upload function in controller looks like this:
function multiple_upload()
{
$config['upload_path'] = './userpics/originals/'; // server directory
$config['allowed_types'] = 'gif|jpg|png'; // by extension, will check for whether it is an image
$config['max_size'] = '512'; // in kb
//$config['max_width'] = '1024';
//$config['max_height'] = '768';
$this->load->library('myupload');
$error = array(); $data = array();
for ($i=0;$i<count($_FILES['userfile']['name']);$i++) {
$this->myupload->initialize($config);
if (!$this->myupload->do_upload('userfile',$i)) {
$error[] = $this->myupload->display_errors();
}
$data[$i] = $this->myupload->data(); //gradually build up upload->data()
}
if ( count($error) > 0 )
{
print_r($error);
}
else
{
print_r($data);
}
}
At this point I made a copy of CI upload class, and pasted it into my applications library directory. A few changes need to be made. I named it myupload.
# Line 143:
public function do_upload($field = 'userfile')
change to
public function do_upload($field = 'userfile', $i = 0)
Any lines in this function above line 200, you must add [$i] to the end of the $_FILES variables.
Example:
is_uploaded_file($_FILES[$field]['tmp_name'])
change to:
is_uploaded_file($_FILES[$field]['tmp_name'][$i])
There are 9 lines to be updated.
Are you sure that you get an array? is see several return FALSE. So you should check,
if ($files !== FALSE)
or casting it to an (empty) array (if false returns) with
$files = (array) $this->multi_upload->go_upload();