uploading multiple image in codeigniter using same input - codeigniter

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();
}
}

Related

How to get/view images dynamically in homepage using CodeIgniter?

image
New_model
=========
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class New_model extends CI_Model
{
private $_table = "news";
public $title;
public $date;
public $description;
public $image = "default.jpg";
public $url;
public function rules()
{
return [
['field' => 'title',
'label' => 'Title',
'rules' => 'required'],
['field' => 'date',
'label' => 'Date',],
// 'rules' => 'required'],
['field' => 'description',
'label' => 'Description',
'rules' => 'required']
];
}
public function getAll()
{
return $this->db->get($this->_table)->result();
}
public function getById($id)
{
return $this->db->get_where($this->_table, ["new_id" => $id])->row();
}
public function save()
{
$post = $this->input->post();
// $this->new_id = uniqid();
$this->title = $post["title"];
$this->date = $post["date"];
$this->description = $post["description"];
$this->image = $this->_uploadImage();
$this->db->insert($this->_table, $this);
// $this->url = base_url() . 'uploads/';
$post['url'] = base_url() . 'uploads/';
}
public function update()
{
$post = $this->input->post();
$this->new_id = $post["id"];
$this->title = $post["title"];
$this->date = $post["date"];
$this->description = $post["description"];
if (!empty($_FILES["image"]["name"])) {
$this->image = $this->_uploadImage();
} else {
$this->image = $post["old_image"];
}
$this->db->update($this->_table, $this, array('new_id' => $post['id']));
}
public function delete($id)
{
$this->_deleteImage($id);
return $this->db->delete($this->_table, array("new_id" => $id));
}
private function _uploadImage()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
// $config['file_name'] = $this->new_id;
$config['overwrite'] = true;
$config['max_size'] = 1024; // 1MB
// $config['max_width'] = 1024;
// $config['max_height'] = 768;
$this->load->library('upload', $config);
if ($this->upload->do_upload('image')) {
return $this->upload->data("file_name");
}
return "default.jpg";
}
private function _deleteImage($id)
{
$new = $this->getById($id);
if ($new->image != "default.jpg") {
$filename = explode(".", $new->image)[0];
return array_map('unlink', glob(FCPATH."uploads/$filename.*"));
}
}
}
public function single($id)
{
$data['news'] = $this->New_model->where('new_id',$id)->order_by('new_id','desc')->get_all();
$data['news1'] = $this->New_model->limit(5)->order_by('id','desc')->get_all();
$this->current = 'news';
$this->load->view(['current' => $this->current]);
$this->load->view('news',$data);
}
Controller
==========
public function index()
{
$data["news"] = $this->New_model->getAll();
$this->load->view('index',$data);
}
public function latestnews()
{
$data['news'] = $this->New_model->where('new_id',$id)->order_by('new_id','desc')->get_all();
$this->load->view('news',$data);
}
view
====
<?php
if (isset($news) and $news) {
foreach ($news as $new) {
?>
<div class="tile-primary-content">
<img src="<?php echo $new->url . $new->image;?>" alt="image" />
</div>
<div class="tile-secondary-content">
<div class="section-title-1">
<span class="title"><?php echo $new->title;?></span>
</div>
<h2 class="heading-20"><?php echo $new->date;?></h2>
</div>
<?php
}
}
?>
I'm trying to upload an image in the dashboard with a title and date along with the image upload.
How to display that image on the homepage?
How to set the URL in the New_model?
How to set the links to display the images in the homepage?
How to set the date links?
The title field can be viewed in the homepage, but no image and dateā€¦
Try this code.
Controller: (Edited)
function index() {
$this->data["news"] = $this->new_model->getAll();
$this->load->view('index', $this->data);
}
function single_news($id) {
$this->data['news_data'] = $this->new_model->getNewsByID($id);
$this->load->view('single-news', $this->data); // Create New View file named single-news.php
}
function add_news() {
$image_status = FALSE;
$this->load->library('form_validation');
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('description', 'Description', 'required');
if($this->form_validation->run() == TRUE) {
$image_name = NULL;
if ($_FILES['image']['size'] > 0) {
$this->load->library('upload');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if( ! $this->upload->do_upload('image')){
$this->data['error'] = $this->upload->display_errors();
}
$image_name = $this->upload->file_name;
$image_status = TRUE;
}
$data = array(
'title' => $this->input->post('title'),
'date' => $this->input->post('date')?date('Y-m-d', strtotime($this->input->post('date'))):NULL,
'description' => $this->input->post('description'),
'image' => $image_name
);
}
if($this->form_validation->run() == TRUE && $image_status && $this->new_model->addNews($data)) {
$this->session->set_flashdata('message', 'News has been created successfully.');
redirect('index');
} else {
$this->data['error'] = (validation_errors()) ? validation_errors() : $this->session->flashdata('error');
$this->data['page_title'] = 'Add News';
$this->load->view('add_news', $this->data);
}
}
When adding new News you don't need to add the uploaded location (Not necessary).
Model: (Edited)
function getAll() {
$q = $this->db->get('news');
if($q->num_rows() > 0) {
foreach($q->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
function getNewsByID($id) {
$this->db->where('id', $id);
$q = $this->db->get('news');
if($q->num_rows() > 0) {
return $q->row();
}
return false;
}
function addNews($data) {
if($this->db->insert('news', $data)){
return true;
}
return false;
}
View: (Edited)
<?php
if ($news) {
foreach ($news as $new) {
?>
<div class="tile-primary-content">
<a href="<?php echo base_url('single_news/'.$new->id); ?>"
<img src="<?php echo site_url('uploads/'.$new->image); ?>" alt="image" />
</a>
</div>
<div class="tile-secondary-content">
<div class="section-title-1">
<span class="title"><?php echo $new->title;?></span>
</div>
<h2 class="heading-20"><?php echo !is_null($new->date)?date('d.m.Y', strtotime($new->date)):' - ';?></h2>
</div>
<?php
}
}
?>
single-news.php: (View)
...
<img src="<?php echo site_url('uploads/'.$news_data->image); ?>" />
...

Photo Upload together with some data won't work. I used batch_insert in my model

This is the View.php file
<input name="u_code[]" required="required" style="margin:0px; ">
<input name="u_name[]" required="required" style="margin:0px; ">
<input name="u_address[]" required="required" style="margin:0px; ">
<input name="photo[]" required="required" style="margin:0px; ">
This is my Controller inserting multiple data but I want to include upload photo.Unfortunately it will not run.
My table has a field for User ID, User Code, Username, User address the lastly the photo of each user.
function user_add()
{
if ($_POST)
{
$u_id =$this->input->post('u_id');
$u_code =$this->input->post('u_code');
$u_name =$this->input->post('u_name');
$u_address = $this->input->post('u_address');
if(!empty($_FILES['photo']['name']))
{
$upload = $this->_do_upload();
$data['photo'] = $upload;
} $data = array();
for ($i = 0; $i < count($this->input->post('u_id')); $i++)
{
$data[$i] = array(
'u_id' => $u_id[$i],
'u_code' => $u_code[$i],
'u_name' => $u_name[$i],
'u_address' => $u_address[$i],
);
}
$insert = $this->user_model->user_add($data);
echo json_encode(array("status" => TRUE));
}
}
This part is the function to upload photo.
public function photo_upload()
{
$config['upload_path'] = 'upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100; //set max size allowed in Kilobyte
$config['max_width'] = 1000; // set max width image allowed
$config['max_height'] = 1000; // set max height allowed
$config['file_name'] = round(microtime(true) * 1000); //just milisecond timestamp fot unique name
$this->load->library('upload', $config);
if(!$this->upload->photo_upload('photo')) //upload and validate
{
$data['inputerror'][] = 'photo';
$data['error_string'][] = 'Upload error: '.$this->upload->display_errors('',''); //show ajax error
$data['status'] = FALSE;
echo json_encode($data);
exit();
}
return $this->upload->data('file_name');
}
**Model:**
public function user_add($data)
{
$this->db->insert_batch($this->table, $data);
return $this->db->insert_id();
}
This is the Actual forms picture:

How to use Multiple images in codeigniter

In my page I want user to select multiple images and upload it I am saving images name in database for reference. I am successful in uploading single images in database and can also show image in view but now I have problem in uploading multiple images.
public function add_record()
{
$this->form_validation->set_rules('category', 'category', 'required');
$current_date = date("Y-m-d H:i:s");
$error='';
if($this->form_validation->run())
{
$image = '';
if($_FILES['image']['name'])
{
if (!is_dir('/backend_assets/media/image/')) {
mkdir('./backend_assets/media/image/', 0777, TRUE);
}
$config['upload_path'] = './backend_assets/media/image/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$data = $this->upload->data();
$image = $data['file_name'];
}else{
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect(base_url('admin/image'));
}
}
$insert_array = array(
'gl_cat_id' => $this->input->post('category'),
'gl_image'=> $image
);
if ($this->common_model->add_records('vm_image',$insert_array))
{
$id = $this->db->insert_id();
$insert_sco_details = array(
'sd_ty'=>'vm_image',
'sd_ty_id'=>$id,
'sd_image'=>$image
);
if($this->common_model->publication('vm_image',$id) && $this->common_model->add_records('vm_seo_detail',$insert_sco_details))
{
$this->session->set_flashdata('success','Record added successfully');
redirect(base_url('admin/image'));
}else{
$this->session->set_flashdata('error','Error while adding record');
redirect(base_url('admin/image'));
}
}else{
$this->session->set_flashdata('error','Error while adding record');
redirect(base_url('admin/image'));
}
}
$where_array = array('vm_publications.status !=' => 4);
$data['users_type'] = $this->common_model->get_records('vm_image_category','','','');
$data['include'] = 'backend/image/add_image';
$this->load->view('backend/container', $data);
}
How is it possible with above code...?
$current_date = date("Y-m-d H:i:s");
$error = '';
$image = '';
if(isset($_FILES['image']['name']))
{
//print_r($_FILES);
$id = base64_decode($this->input->post('gid'));
$filesCount = count($_FILES['image']['name']);
$inserted = '';
for($i = 0; $i < $filesCount; $i++)
{
$_FILES['userFile']['name'] = $_FILES['image']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['image']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['image']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['image']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['image']['size'][$i];
$config['upload_path'] = './backend_assets/media/image/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('userFile'))
{
$fileData = $this->upload->data();
$image = $fileData['file_name'];
$insert_array = array(
'gl_cat_id' => $this->input->post('category'),
'gl_image'=> $image
);
if ($this->common_model->add_records('vm_image',$insert_array))
{
$id = $this->db->insert_id();
$insert_sco_details = array(
'sd_ty'=>'vm_image',
'sd_ty_id'=>$id,
'sd_image'=>$image
);
if($this->common_model->publication('vm_image',$id) && $this->common_model->add_records('vm_seo_detail',$insert_sco_details))
{
$inserted++;
}
}
}
}
if($inserted == $filesCount)
{ $this->session->set_flashdata('success','Images uploaded successfully');
redirect(base_url('adminp8AamG6ueHFNGAAp/image'));
}else{
$this->session->set_flashdata('error','Error while adding record');
redirect(base_url('adminp8AamG6ueHFNGAAp/image'));
}
}
$where_array = array('vm_publications.status !=' => 4);
$data['users_type'] = $this->common_model->get_records('vm_image_category','','','');
$data['include'] = 'backend/image/add_image';
$this->load->view('backend/container', $data);
try below code in you add_record() function. it will helpful to you. few days ago, i have faced same problem
$files = $_FILES;
$count = count($_FILES['image']['name']);
for($i=0; $i<$count; $i++) {
$_FILES['image']['name']= $files['image']['name'][$i];
$_FILES['image']['type']= $files['image']['type'][$i];
$_FILES['image']['tmp_name']= $files['image']['tmp_name'][$i];
$_FILES['image']['error']= $files['image']['error'][$i];
$_FILES['image']['size']= $files['image']['size'][$i];
$this->upload->initialize($this->set_upload_options());//function defination below
$this->upload->do_upload('image');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name'];
$fileName = $upload_data['file_name'];
$images[] = $fileName;
}
$fileName = $images;
and set file upload configuration in set_upload_options function in same controller.
function set_upload_options() {
$config = array();
$config['upload_path'] = PATH;
$config['remove_spaces']=TRUE;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '78000';
return $config;
}
First, debug the output of the $_FILES variable. This should give you an array of files that are being uploaded. Loop through them to treat each one individually.
foreach ($_FILES as $file) {
// do some file processing on the $file object instead of $_FILES object.
// example: instead of using 'if($_FILES['image']['name'])'
// use: 'if($file['image']['name'])'
}
If you want to use CI's upload class, check out their Docs here: https://www.codeigniter.com/userguide3/libraries/file_uploading.html

Redirect stopping multiple file upload CodeIgniter 3.0.4

I am trying to use redirect on my filemanager controller on my upload function when the form is success full.
How ever when I have the redirect('filemanager') on my success part of form it stops multiple files from being uploaded and then only uploads one.
But when I comment it out like so // redirect('filemanager') I can
upload multiple images fine.
Question: How can I still use my redirect on success form but make sure it uploads the multiple images that is selected rather than just one.
Controller
<?php
class Filemanager extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('upload');
}
public function index() {
$data['title'] = 'File Manager';
$data['template'] = 'template/common/filemanager_view';
$this->load->view('template/common/template_view', $data);
}
public function upload() {
$files = $_FILES;
if ($files) {
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++) {
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$url = '';
$directory = $this->input->get('directory');
if (isset($directory)) {
$url .= $directory . '/';
} else {
$url .= '';
}
$config['upload_path'] = FCPATH . 'images/catalog/' . $url;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
// reminder todo some error code here
} else {
redirect('filemanager');
}
}
}
}
}
I have got it working now thanks to #Vinie suggestion
<?php
class Filemanager extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->library('upload');
}
public function index($results = NULL) {
$data['title'] = 'File Manager';
$data['upload_data'] = array();
if ($results) {
foreach ($results as $result) {
$data['upload_data'][] = array(
'file_name' => $result['file_name']
);
}
}
$upload_errors = $this->upload->display_errors();
if (isset($upload_errors)) {
$data['upload_errors'] = $upload_errors;
} else {
$data['upload_errors'] = '';
}
$data['template'] = 'template/common/upload_view';
$this->load->view('template/common/template_view', $data);
}
public function upload() {
$files = $_FILES;
if ($files) {
$check_if_any_error = 0;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++) {
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$url = '';
$directory = $this->input->get('directory');
if (isset($directory)) {
$url .= $directory . '/';
} else {
$url .= '';
}
$config['upload_path'] = FCPATH . 'images/catalog/' . $url;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$check_if_any_error++;
} else {
$results[] = $this->upload->data();
}
}
if($check_if_any_error > 0 ) {
$this->index();
} else {
$this->index($results);
}
} else {
redirect('filemanager');
}
}
}

Uploading an image in codeigniter

I am trying to upload an image,create thumbnail but i get an error.
Here is my controller.
<?php
class Upload extends Controller {
function Upload()
{
parent::Controller();
$this->load->helper(array('form','url','file'));
}
function index()
{
$this->load->view('upload_form'); //Upload Form
}
function picupload()
{
//Load Model
$this->load->model('Process_image');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048'; //2 meg
$this->load->library('upload');
foreach($_FILES as $key => $value)
{
if( ! empty($key['name']))
{
$this->upload->initialize($config);
if ( ! $this->upload->do_upload($key))
{
$errors[] = $this->upload->display_errors();
}
else
{
$this->Process_image->process_pic();
}
}
}
$data['success'] = 'Thank You, Files Upladed!';
$this->load->view('upload_success', $data); //Picture Upload View
}
}
?>
My model:
<?php
class Process_image extends Model {
function Process_image()
{
parent::Model();
$this->load->library('image_lib');
//Generate random Activation code
function generate_code($length = 10){
if ($length <= 0)
{
return false;
}
$code = "";
$chars = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
srand((double)microtime() * 1000000);
for ($i = 0; $i < $length; $i++)
{
$code = $code . substr($chars, rand() % strlen($chars), 1);
}
return $code;
}
}
function process_pic()
{
//Connect to database
$this->load->database();
//Get File Data Info
$uploads = array($this->upload->data());
$this->load->library('image_lib');
//Move Files To User Folder
foreach($uploads as $key[] => $value)
{
//Gen Random code for new file name
$randomcode = generate_code(12);
$newimagename = $randomcode.$value['file_ext'];
//Creat Thumbnail
$config['image_library'] = 'GD2';
$config['source_image'] = $value['full_path'];
$config['create_thumb'] = TRUE;
$config['thumb_marker'] = '_tn';
$config['master_dim'] = 'width';
$config['quality'] = 75;
$config['maintain_ratio'] = TRUE;
$config['width'] = 175;
$config['height'] = 175;
$config['new_image'] = '/pictures/'.$newimagename;
//$this->image_lib->clear();
$this->image_lib->initialize($config);
//$this->load->library('image_lib', $config);
$this->image_lib->resize();
//Move Uploaded Files with NEW Random name
rename($value['full_path'],'/pictures/'.$newimagename);
//Make Some Variables for Database
$imagename = $newimagename;
$thumbnail = $randomcode.'_tn'.$value['file_ext'];
$filesize = $value['file_size'];
$width = $value['image_width'];
$height = $value['image_height'];
$timestamp = time();
//Add Pic Info To Database
$this->db->set('imagename', $imagename);
$this->db->set('thumbnail', $thumbnail);
$this->db->set('filesize', $filesize);
$this->db->set('width', $width);
$this->db->set('height', $height);
$this->db->set('timestamp', $timestamp);
//Insert Info Into Database
$this->db->insert('pictures');
}
}
}
?>
The error:
A PHP Error was encountered
Severity: Warning
Message: rename(C:/wamp/www/uploads/Heaven_Clouds.jpg,/pictures/kFttl7lpE7Rk.jpg) [function.rename]: No such file or directory
Filename: models/Process_image.php
Line Number: 68
This is line 68:
rename($value['full_path'],'/pictures/'.$newimagename);
Remove the "/" before "picutres" in
rename($value['full_path'],'/pictures/'.$newimagename);
It wanna say that you want put your renamed file in a directory named "pictures" placed at the root of an Unix file system, then you're obviously in a Windows system and you do not seem to have a "pictures" directory at the root of your disk.
result :
rename($value['full_path'],'pictures/'.$newimagename);
This is a very simple script taken partly from the CI Docs:
$config['upload_path'] = 'uploads/cgm/';
$config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
$configThumb = array();
$configThumb['image_library'] = 'gd2';
$configThumb['source_image'] = '';
$configThumb['create_thumb'] = TRUE;
$configThumb['maintain_ratio'] = TRUE;
$configThumb['width'] = 100;
$configThumb['height'] = 120;
$this->load->library('image_lib');
for($i = 1; $i < 6; $i++) {
$upload = $this->upload->do_upload('file'.$i);
if($upload === FALSE) continue;
$data = $this->upload->data();
$uploadedFiles[$i] = $data;
$imgName = $this->pictures_m->addPicture(array('listing_id' => $listing_id, 'ext' => $data['file_ext'], 'picture_name' => $this->input->post('file'.$i.'name')));
if($data['is_image'] == 1) {
$configThumb['source_image'] = $data['full_path'];
$configThumb['new_image'] = $data['file_path'].$imgName.$data['file_ext'];
$this->image_lib->initialize($configThumb);
$this->image_lib->resize();
}
rename($data['full_path'], $data['file_path'].$imgName.$data['file_ext']);
}
this will take 5 images, but if you only have one, you can just change the for loop.
i had the same problem but, in my scenario i've to only upload the array of files so i did some small changes to the library 'Upload.php'
view
<form encrypt="multipart/form-data" ...>
<input type="file" name="your_name[]" />
<input type="file" name="your_name[]" />
<input type="submit" />
</form>
controller
for($i = 0; $i < count($_FILES['your_name']['name']); $i++) {
$config['upload_path'] = 'your upload path';
$this->upload->initialize($config);
$this->upload->do_upload('listing_images', $i);
endfor;
if you have single file to upload then duplicate the function in system/libraries/Upload.php
function do_upload($field) to function do_upload_array($field, $i)
put [$i] index on lines 160, 162, 196, 197
and
function _file_mime_type($_FILES[$field]) to function _file_mime_type_array($_FILES[$field], $i)
and put [$i] index on lines 1026, 1043, 1057 and 1065
thats it...
your file array will upload easily now....

Resources