When I upload multiple images I would like to be able to display each file name.
I can upload the file fine in to the upload folder, but when I try to get the multiple file_name data it shows error below.
I get this error below
Severity: Warning Message: Illegal string offset 'file_name' Filename:
page/Page_add.php Line Number: 110
Which is here in success part of upload function
$upload_info = $this->upload->data();
foreach ($upload_info as $upload_data) {
echo $upload_data['file_name']; // Line 110
}
Do upload function
public function do_upload() {
$directory = FCPATH . 'uploads/';
if (is_dir($directory)) {
foreach ($_FILES as $field_name => $value) {
if ($value['name'] != '') {
$this->load->library('upload');
$this->upload->initialize($this->do_upload_options());
if (!$this->upload->do_upload($field_name)) {
$this->form_validation->set_message('do_upload', $this->upload->display_errors());
return FALSE;
} else {
$upload_info = $this->upload->data();
foreach ($upload_info as $upload_data) {
echo $upload_data['file_name'];
}
}
}
}
} else {
$this->form_validation->set_message('do_upload', 'Cannot Find Directory' .' '. $directory);
return FALSE;
}
}
public function do_upload_options() {
$config = array();
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|png|jpg';
$config['max_size'] = '30000';
$config['overwrite'] = TRUE;
$config['max_width'] = '0';
$config['max_height'] = '0';
return $config;
}
Each field name has its own name="" example name="fileupload_extra_image0" the number at the end is automatically generated
Vardump
array(2) { ["fileupload_extra_image0"]=> array(14) { ["file_name"]=> string(17) "ci_logo_flame.jpg" ["file_type"]=> string(10) "image/jpeg" ["file_path"]=> string(49) "C:/Xampp/htdocs/riwakawebsitedesigns-cms/uploads/" ["full_path"]=> string(66) "C:/Xampp/htdocs/riwakawebsitedesigns-cms/uploads/ci_logo_flame.jpg" ["raw_name"]=> string(13) "ci_logo_flame" ["orig_name"]=> string(17) "ci_logo_flame.jpg" ["client_name"]=> string(17) "ci_logo_flame.jpg" ["file_ext"]=> string(4) ".jpg" ["file_size"]=> float(3.61) ["is_image"]=> bool(true) ["image_width"]=> int(100) ["image_height"]=> int(100) ["image_type"]=> string(4) "jpeg" ["image_size_str"]=> string(24) "width="100" height="100"" } ["fileupload_extra_image1"]=> array(14) { ["file_name"]=> string(10) "family.png" ["file_type"]=> string(9) "image/png" ["file_path"]=> string(49) "C:/Xampp/htdocs/riwakawebsitedesigns-cms/uploads/" ["full_path"]=> string(59) "C:/Xampp/htdocs/riwakawebsitedesigns-cms/uploads/family.png" ["raw_name"]=> string(6) "family" ["orig_name"]=> string(10) "family.png" ["client_name"]=> string(10) "family.png" ["file_ext"]=> string(4) ".png" ["file_size"]=> float(828.1) ["is_image"]=> bool(true) ["image_width"]=> int(670) ["image_height"]=> int(450) ["image_type"]=> string(3) "png" ["image_size_str"]=> string(24) "width="670" height="450"" } }
public function do_upload()
{
$directory = FCPATH . 'uploads/';
$upload_info = [];//array();
if (is_dir($directory)) {
foreach ($_FILES as $field_name => $value) {
if ($value['name'] != '') {
$this->load->library('upload');
$this->upload->initialize($this->do_upload_options());
if (!$this->upload->do_upload($field_name)) {
$this->form_validation->set_message('do_upload', $this->upload->display_errors());
return FALSE;//You would like to make better control here because first one is not file_name would break process
} else {
$upload_info[$field_name] = $this->upload->data();
}
}
}
if ( count($upload_info) > 0 ) {
foreach ($upload_info as $upload_data) {
echo $upload_data['file_name'];
}
}
} else {
$this->form_validation->set_message('do_upload', 'Cannot Find Directory' .' '. $directory);
return FALSE;
}
}
public function do_upload_options()
{
$config = array();
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|png|jpg';
$config['max_size'] = '30000';
$config['overwrite'] = TRUE;
$config['max_width'] = '0';
$config['max_height'] = '0';
return $config;
}
Related
i try to upload image and insert it into database but it's not working.
there is no any error showing in page and image is also not uploading or inserting into database,
please, give me a solution for that how can i solved this problem?
my code is here,
the code of controller is here, enter code here
public function add_product()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$input_name = "product_image";
if (!$this->upload->do_upload($input_name))
{
$data['items'] = $this->data_model->get_data_info('product_id','product');
$this->load->view('product',$data);
}
else
{
$image_info = $this->upload->data();
$data = array(
'product_name'=>$this->input->post('product'),
'product_pic'=>$image_info['file_name'],
'description'=>$this->input->post('description')
);
$query = $this->data_model->add_data($data,'product');
if($query == TRUE){
echo "product added";
$data['items'] = $this->data_model->get_data_info('product_id','product');
$this->load->view('product',$data);
}else{
echo"product already exists";
$data['items'] = $this->data_model->get_data_info('product_id','category');
$this->load->view('product',$data);
}
}
}
model :
public function add_data($data,$table){
$result = $this->db->get_where($table,$data);
$query = (bool)$result->num_rows();
if(!$query){
if($this->db->insert($table,$data)){
return TRUE;
}else{
return FALSE;
}
}else{
return FALSE;
}
}
controller code
function add_product() {
if (!is_dir('./Uploads/')) {
mkdir('./Uploads/', 0777, TRUE);
}
if (!empty($_FILES['product_image'])) {
$config['upload_path'] = './Uploads/';
$config['allowed_types'] = '*';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['overwrite'] = TRUE;
$config['file_name'] = date('U') . '_' . $_FILES['product_image']['name'];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('product_image')) {
$error = array('error' => $this->upload->display_errors());
print_r($error);
die;
} else {
if ($this->upload->do_upload('product_image')) {
$image_data = $this->upload->data();
$full_path = $config['file_name'];
$data["product_pic"] = $full_path;
$query = $this->data_model->add_data($data, 'product');
if ($res == TRUE) {
echo "product added";
$data['items'] = $this->data_model->get_data_info('product_id', 'product');
$this->load->view('product', $data);
} else {
echo"product already exists";
$data['items'] = $this->data_model->get_data_info('product_id', 'category');
$this->load->view('product', $data);
}
}
}
}
$this->load->view('product');
}
model code
function add_data($data, $table) {
if ($query = $this->db->insert($table,$data)) {
$insert_id = $this->db->insert_id();
return $insert_id;
} else {
return false;
}
}
views
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="userfile[]" size="40" multiple/>
<input type="submit" name="submit" value="Upload">
</form>
controller
public function image()
{
$data['error'] = '';
$this->load->model('StackM');
if(isset($_POST['submit']))
{
$data['update_pass_error_msg'] = $this->StackM->add_multiple_image();
}
$this->load->view('stack_view');
}
Model
public function add_multiple_image(){
if((!empty($_FILES['f2']['name'])))
{
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$files = $_FILES;
if ($files['f2']['name'][0] == '' )
{
# code...
return "Select a file to upload";
}
else
{
$mum_files = count($files['f2']);
for($i=0; $i<$mum_files; $i++)
{
if ( isset($files['f2']['name'][$i]) )
{
$config['file_name'] = time().'-'.$files['f2']['name'][$i];
$this->load->library('upload', $config);
$_FILES['f2']['name']= $files['f2']['name']["$i"];
$_FILES['f2']['type']= $files['f2']['type']["$i"];
$_FILES['f2']['tmp_name']= $files['f2']['tmp_name']["$i"];
$_FILES['f2']['error']= $files['f2']['error']["$i"];
$_FILES['f2']['size']= $files['f2']['size']["$i"];
$filename = rand().'-'.$_FILES['f2']['name'];
if (!empty($this->upload->do_upload('f2')))
{
$dataInfo[] = $this->upload->data();
$all_imgs = '';
if ( count($dataInfo) > 0) {
# code...
foreach ($dataInfo as $info) {
# code...
$all_imgs .= $info['file_name'];
$all_imgs .= ',';
}
}
}
}
}
}
}
else{
$all_imgs = "";
}
}
}
else{
$all_imgs = $this->session->userdata('image');
}
$this->db->insert('table_name', $all_imgs);
The problem I am facing in this code is Think suppose if I am adding 7 images, but it's showing only 5 images in database it's not taking more then five and also I want to know while editing the form if I don't want to change the image then it should remain same image so i have stored the old image in session and checking if it is empty then only it should session variable .
But In my code if I will not upload new one If I keep old image as then it will save blank
To avoid the offset error, inside of for loop you need to check if that array index is set or not:
Here I have a demo code to upload multiple files in CodeIgniter:
views/stack_view.php
<?php if ($this->session->flashdata('status')) { ?>
<h5><?=$this->session->flashdata('status')?>: <?=$this->session->flashdata('message')?></h5>
<?php } ?>
<?=form_open_multipart('stack', array('id' => 'my_id'))?>
<input type="file" name="userfile[]" size="40" multiple/>
<input type="submit" name="submit" value="Upload">
<?=form_close()?>
controllers/Stack.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Stack extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper(array('form', 'url'));
}
public function index()
{
if ($this->input->post('submit')) {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$files = $_FILES;
if ($files['userfile']['name'][0] == '' ) {
# code...
$this->session->set_flashdata('status', 'error');
$this->session->set_flashdata('message', "Select a file to upload");
}
else
{
$mum_files = count($files['userfile']);
$dataInfo = array();
for($i=0; $i<$mum_files; $i++)
{
if ( isset($files['userfile']['name'][$i]) ) {
$config['file_name'] = time().'-'.$files['userfile']['name'][$i];
$this->load->library('upload', $config);
$_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"];
$filename = rand().'-'.$_FILES['userfile']['name'];
if ( ! $this->upload->do_upload('userfile'))
{
$error_message = $this->upload->display_errors();
$this->session->set_flashdata('status', 'error');
$this->session->set_flashdata('message', "$error_message");
}
else
{
//$data = array('upload_data' => $this->upload->data());
$this->session->set_flashdata('status', 'success');
$this->session->set_flashdata('message', "Files upload is success");
}
$dataInfo[] = $this->upload->data(); //all the info about the uploaded files are stored in this array
}
}
//here you can insert all the info about uploaded file into database using $dataInfo
$all_imgs = '';
if ( count($dataInfo) > 0) {
# code...
foreach ($dataInfo as $info) {
# code...
$all_imgs .= $info['file_name'];
$all_imgs .= ',';
}
}
$insert_data = array(
'your_column_name' => rtrim($all_imgs,",")
);
$this->db->insert('your_table_name', $insert_data);
}
}
$this->load->view('stack_view');
}
}
Try this script and I hope you will get some help from this.
This is working script try to upload it
public function upload()
{
$this->load->library('session');
if ( ! empty($_FILES))
{
$config['upload_path'] = "assets/uploads/";
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = 5120; //limit only 5 Mb
$this->load->library('upload');
$files = $_FILES;;
$number_of_files = count($_FILES['files']['name']);
$errors = 0;
$myname = $this->input->post('ad_title');
for ($i = 0; $i < $number_of_files; $i++)
{
//$randVal = rand(450,4550).time('d-y-m');
$filename = basename($files['files']['name'][$i]);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = md5($filename.''.time('d-y-m')).'.'.$extension;
$_FILES['files']['name'] = $new; //$files['files']['name'][$i];
$_FILES['files']['type'] = $files['files']['type'][$i];
$_FILES['files']['tmp_name'] = $files['files']['tmp_name'][$i];
$_FILES['files']['error'] = $files['files']['error'][$i];
$_FILES['files']['size'] = $files['files']['size'][$i];
$image = array('upload_data' => $this->upload->data());
$image_name = $_FILES['files']['name'];
$ip = $this->input->ip_address();
$this->session->set_userdata("userIP",$ip);
//$this->session->unset_userdata("userIP");
$Dval = array(
"filename" => $image_name,
"ip" => $this->input->ip_address()
);
$this->member_model->tmp_image($Dval);
$this->upload->initialize($config);
if ( $this->upload->do_upload("files"))
{
$errors++;
$data = $this->upload->data();
echo json_encode($data['file_name']);
//code is for thumbnail and watermark on images
//$this->watermark($data['full_path']);
//$myPathfT = $config1['upload_path'] = "./assets/thumbs/".$aDir;
//mkdir($myPathfT);b
$config1 = array();
$config1['image_library'] = 'gd2';
$config1['source_image'] = $data['full_path'];
$config1['new_image'] = 'assets/uploads/thumbs/';
$config1['create_thumb'] = false;
$config1['quality'] = 50;
$config1['height'] = 150;
$config1['width'] = 150;
$this->load->library('image_lib',$config1);
$this->image_lib->initialize($config1);
$this->image_lib->resize();
$this->image_lib->clear();
}
}
if ($errors > 0)
{
//echo "Data Transferred";
}
}
elseif ($this->input->post('file_to_remove'))
{
$aDir = $this->session->userdata('Dir');
$file_to_remove = $this->input->post('file_to_remove');
unlink("./assets/mainFilesData/$aDir/" . $file_to_remove);
$array = $this->session->userdata('photo');
$dataF = array_diff($array, array($file_to_remove));
$this->session->set_userdata('photo',$dataF);
}
else
{
$this->listFiles();
}
}
I do not understand how to fix this codes:
return $this->db->update('slideshow');
I have tried several codes like changing it to $query or $query_result etc. and the error still exist. I still have to use $this->db->update('');
controllers/Cuploadfile.php
function uploadedit()
{
$data['images'] = ''; // Need to place it here and get images here.
//set preferences
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|gif';
$config['max_size'] = '500000';
//load upload class library
$this->load->library('upload', $config);
$this->load->model('Mpages');
if (!$this->upload->do_upload('filename'))
{
// case - failure
$upload_error = array('error' => $this->upload->display_errors());
$this->load->view('addslideshows', $upload_error);
}
else
{
// case - success
$upload_data = $this->upload->data();
$filename = $upload_data['file_name'];
$image_id = $this->uri->segment(3);
$data['images'] = $this->Mpages->edit_slideshow($filename, $image_id);
$data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . $upload_data['file_name'] . '</strong> was successfully uploaded!</div>';
$this->load->view('editslideshows', $data);
}
}
models/Mpages.php
public function edit_slideshow($filename, $image_id)
{
$this->db->set('slideshow_image', $filename);
$this->db->where('image_id', $image_id);
return $this->db->update('slideshow');
}
Change your Model's function to this
public function edit_slideshow($filename, $image_id){
$this->db->where('image_id', $image_id);
$this->db->update('slideshow', $filename);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
rewrite your model
public function edit_slideshow($filename, $image_id)
{
$this->db->set('slideshow_image', $filename);
$this->db->where('image_id', $image_id);
$update=$this->db->update('slideshow');
if($update)
{
return true;
}
return false;
}
Question: When the user has filled in the form validation correct but there is a error on image upload how is it possible to stop the form being submitted
Currently still submits data even if there is a error on my image upload.
<?php
class Users extends MY_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('countries');
$this->load->library('upload');
$this->load->model('admin/user/user_model');
$this->load->model('admin/user_group/usergroup_model');
}
public function add() {
$this->form_validation->set_rules('username', 'Username', 'trim|required');
if ($this->form_validation->run() == true) {
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0) {
if (!is_dir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/')) {
mkdir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/');
}
$config['upload_path'] = './uploads/users/' . $this->input->post('username') . '/';
$config['allowed_types'] = 'gif|png';
$config['max_size'] = 3000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if ($this->upload->do_upload('userfile')) {
return true;
}
}
$this->user_model->insert($this->upload->data());
}
if ($this->upload->display_errors() != false) {
$this->error['warning'] = $this->upload->display_errors();
}
if (validation_errors() != false) {
$this->error['warning'] = validation_errors('<div class="alert alert-danger">', '</div>');
}
if (isset($this->error['warning'])) {
$data['warning_error'] = $this->error['warning'];
} else {
$data['warning_error'] = '';
}
$data['countries'] = $this->countries->get();
$data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
$data['usergroups'] = $this->usergroup_model->get_user_groups();
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('user/add_view', $data);
}
}
Model
<?php
class User_model extends CI_Model {
public function insert($upload_data = array()) {
$this->db->trans_begin();
$options = [
'cost' => 12,
];
$hash = password_hash($this->input->post('password'), PASSWORD_BCRYPT, $options);
$data = array(
'user_group_id' => $this->input->post('user_group_id'),
'username' => $this->input->post('username'),
'password' => $hash,
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'email' => $this->input->post('email'),
'image' => ($upload_data['file_name']) ? $upload_data['file_name'] : '',
'country' => $this->input->post('country'),
'timezone' => $this->input->post('timezone'),
'status' => $this->input->post('status'),
'date_added' => date('Y-m-d')
);
$this->db->set($data);
$this->db->insert($this->db->dbprefix . 'user');
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
} else {
$this->db->trans_commit();
}
}
}
Codeigniter Version 3.1.0 & XAMPP Windows 10
Have solved it now.
<?php
class Users extends MY_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('countries');
$this->load->library('upload');
$this->load->model('admin/user/user_model');
$this->load->model('admin/user_group/usergroup_model');
}
public function add() {
$this->form_validation->set_rules('username', 'username', 'trim|required|is_unique[user.username]');
$this->form_validation->set_message('is_unique', 'Opps looks like someone has all ready got that {field}');
if ($this->form_validation->run() == true) {
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0) {
if ($this->upload() == true) {
$this->user_model->insert($this->upload->data());
}
} else {
$this->user_model->insert();
}
}
if (validation_errors() != '') {
$this->error['warning'] = validation_errors('<div class="alert alert-danger">', '</div>');
}
if (isset($this->error['warning'])) {
$data['warning_error'] = $this->error['warning'];
} else {
$data['warning_error'] = '';
}
$data['countries'] = $this->countries->get();
$data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
$data['usergroups'] = $this->usergroup_model->get_user_groups();
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('user/add_view', $data);
}
public function upload() {
if (!is_dir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/')) {
mkdir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/');
}
$config['upload_path'] = './uploads/users/' . $this->input->post('username') . '/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 3000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile')) {
$this->error['warning'] = $this->upload->display_errors('<div class="alert alert-danger">', '</div>');
} else {
return true;
}
return !$this->error;
}
}
I'm trying to update my information: In the localhost it is not error variable: img, but when i upload it into the server it is error like that A PHP Error was encountered:
Severity: Notice Message: Undefined variable: img Filename: controllers/pages.php Line Number: 79....
function update_ads($id)
{
if($this->input->post('update_ads'))
{
$this->db->select('img');
$this->db->where('id',$id);
$query = $this->db->get('tblp_label_slides',$id);
foreach($query->result() as $row)
{
$img = $row->img;
$image = $this->session->set_userdata('img', $img);
}
if($img!='')
{
$config['upload_path'] ='./images/ads';
$config['allowed_types'] ='jpg|jpeg|gif|png';
$config['max_size'] = 1024*8;
$config['encrypt_name'] = true;
$this->upload->initialize($config);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('imgfile'))
{
$edit['update'] = $this->mod_write->up_adv($this->session->userdata('img'), $id);
$this->session->set_flashdata(array('success_update' => 12));
redirect('pages/ads_right');
}
else
{
$img_content = $this->upload->data('imgfile');
$edit['update'] = $this->mod_write->up_adv($img_content['file_name'], $id);
unlink("./images/ads/".$img);
$this->session->set_flashdata(array('success_update' => 12));
redirect('pages/ads_right');
}
}
else
{
$config['upload_path'] = './images/ads';
$config['allowed_types'] = 'jpg|jpeg|gif|png';
$config['max_size'] = 1024*8;
$config['encrypt_name'] = true;
$this->upload->initialize($config);
$this->load->library('upload', $config);
if(! $this->upload->do_upload('imgfile'))
{
$edit['update'] = $this->mod_write->up_adv('', $id);
$this->session->set_flashdata(array('success_update' => 12));
redirect('pages/ads_right');
}
else
{
$img_content = $this->upload->data('imgfile');
$edit['update'] = $this->mod_write->up_adv($img_content['file_name'], $id);
unlink("./images/ads/".$img);
$this->session->set_flashdata(array('success_update' => 12));
redirect('pages/ads_right');
}
}
}
}
my model
function up_adv($img_content)
{
$id = $this->uri->segment(3);
$data = array(
'dates'=>date('Y-m-d H:i:s'),
'url'=>replace_tag($this->input->post('url')),
'title'=>replace_tag($this->input->post('title')),
'img'=>$img_content,
'type'=>$this->input->post('type')
);
$this->db->where('id',pde($id))
->update('tblp_label_slides',$data);
}
I could be wrong but I think the issue how you are validating $img.
Change if ($img != '')
To if (isset($img) && trim($img) !== '')
This will stop an error being thrown if $img has not been declared which will happen if your query doesn't return any rows.
Hope this helps!