Upload multiple images with codeigniter - php

I have used some code I found before to upload 1 image at a time and this works perfect. I would like to use the same style of code but for multiple images.
The Model:
function cover_upload($afbeelding) {
// path where the picture needs to be uploaded
echo $album_path = APPPATH . 'images/covers';
// configuration for the upload
$ext = end(explode(".", $_FILES['userfile']['name']));
$config = array(
'file_name' => $afbeelding . '.' . $ext,
'upload_path' => $album_path,
'allowed_types' => 'gif|jpg|jpeg|png',
'max_size' => '5120'
);
// load upload library with the configuration
$this->load->library('upload', $config);
// upload picture with the upload library
if (!$this->upload->do_upload()) {
echo $this->upload->display_errors();
die();
}
// get data array of the uploaded picture
$image_data = $this->upload->data();
// configuration for the picture thumbnail resize
echo $image_data['full_path'];
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => realpath($album_path . '/thumb'),
'maintain_ration' => TRUE,
'width' => 300,
'height' => 300
);
// load image manupulation library with the configuration
$this->load->library('image_lib', $config);
// resize picture
$this->image_lib->resize();
$this->image_lib->clear();
// submit file name of the uploaded picture to save it in the database
$bestandsnaam = $image_data['file_name'];
return $bestandsnaam;
}
the view (just the part about the image):
<div class="form-group">
<label class="col-sm-2 control-label" for="CoverFoto">picture</label>
<div class="col-sm-5">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 200px; height: 150px;"></div>
<div>
<span class="btn btn-default btn-file"><span class="fileinput-new">select_an_image</span><span class="fileinput-exists">change</span><input type="file" name="userfile"></span>
<?php echo $this->lang->line("remove"); ?>
</div>
</div>
</div>
</div>
And the controller:
if (!empty($_FILES['userfile']['name'])) {
$gamma->CoverFoto = $this->gamma_model->cover_upload(url_title($gamma->Naam, '_', true));
}
Is there a way to use this code so i can upload multiple images?

Have a look upon this code may this help in understanding you how to handle multiple images
#####################
# Uploading multiple#
# Images #
#####################
$files = $_FILES;
$count = count($_FILES['uploadfile']['name']);
for($i=0; $i<$count; $i++)
{
$_FILES['uploadfile']['name']= $files['uploadfile']['name'][$i];
$_FILES['uploadfile']['type']= $files['uploadfile']['type'][$i];
$_FILES['uploadfile']['tmp_name']= $files['uploadfile']['tmp_name'][$i];
$_FILES['uploadfile']['error']= $files['uploadfile']['error'][$i];
$_FILES['uploadfile']['size']= $files['uploadfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());//function defination below
$this->upload->do_upload('uploadfile');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name'];
$fileName = $upload_data['file_name'];
$images[] = $fileName;
}
$fileName = $images;
what's happening in code??
well $_FILE---->it is an associative array of items uploaded to the current script via the POST method.for further look this LINK
it's an automatic variable avaliable within all scopes of script
function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = LARGEPATH; //give the path to upload the image in folder
$config['remove_spaces']=TRUE;
$config['encrypt_name'] = TRUE; // for encrypting the name
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '78000';
$config['overwrite'] = FALSE;
return $config;
}
and in your html markup don't don't forget:
Input name must be be defined as an array i.e. name="file[]"
Input element must have multiple="multiple" or just multiple
3.$this->load->library('upload'); //to load library
4.The callback, $this->upload->do_upload() will upload the file selected in the given field name to the destination folder.
5.And the callback $this->upload->data() returns an array of data related to the uploaded file like the file name, path, size etc.

Related

resizing image in codeigniter php not working correctly

I am trying to resize multiple images using codeigniter, my file upload code in controller looks like below:
$this->load->library('upload');
$image = array();
$ImageCount = count($_FILES['pimage']['name']);
for($i = 0; $i < $ImageCount; $i++){
$_FILES['file']['name'] = $_FILES['pimage']['name'][$i];
$_FILES['file']['type'] = $_FILES['pimage']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['pimage']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['pimage']['error'][$i];
$_FILES['file']['size'] = $_FILES['pimage']['size'][$i];
// File upload configuration
$uploadPath = './uploads/products/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
// Load and initialize upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
// Upload file to server
if($this->upload->do_upload('file')){
// Uploaded file data
$imageData = $this->upload->data();
$uploadImgData[] = $imageData['file_name'];
$this->resizeImage($imageData['file_name']);
}
}
public function resizeImage($filename)
{
$source_path = './uploads/products/' . $filename;
$target_path = './uploads/products/';
$config_manip = array(
'image_library' => 'gd2',
'source_image' => $source_path,
'new_image' => $target_path,
'maintain_ratio' => TRUE,
'width' => 500,
);
$this->load->library('image_lib', $config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
$this->image_lib->clear();
}
Here I have two issues, first one is only the first image is getting resized, multiple images are not. Second thing is: if portrait image is uploaded its turned into landscape after conversion. Can anyone please tell me what is wrong in here, thanks in advance

I am getting empty array, I need array of image while uploading multiple images in Codeigniter

This code is for getting file name in array.
I am getting an empty array of file.
Here I am attaching the source code for the same issue.
Have look a code and give me some solution
$images = array();
$count = count($_FILES['files']['name']);
for($i = 0; $i < $count ; $i++)
{
if(!empty($_FILES['file']['name'][$i]))
{
$tmp = explode(".",$_FILES['files']['name'][$i]);
$file_extension = end($tmp); //this is temp variable
$imagename = time().".".$file_extension;
// Define new $_FILES array - $_FILES['file']
$_FILES['file']['name'] = $_FILES['files']['name'][$i];
$_FILES['file']['type'] = $_FILES['files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['files']['error'][$i];
$_FILES['file']['size'] = $_FILES['files']['size'][$i];
// Set preference
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|jpeg|png|gif'; // this is allowed file type
$config['file_name'] = $imagename;
//Load upload library
$this->load->library('upload',$config);
if($this->upload->do_upload('file')){
// Get data about the file
$uploadData = $this->upload->data();
$filename = $uploadData['file_name'];
// Initialize array
array_push($images, $filename);
}
}
}
echo "<pre>";print_r($images);die;
Also here I am attaching form code
<?php $attributes = array(
"class" => "form-horizontal m-t-20",
"method" => "post",
"novalidate" => "",
"enctype" => "multipart/form-data"
);
echo form_open('admin/user/adduser', $attributes); ?>
This code for file input
<label for="file">Profile Images*</label>
<input type="file" name="files[]" id="file" multiple required placeholder="Profile Images" class="form-control">
Replace the Line
if(!empty($_FILES['file']['name'][$i]))
to
if(!empty($_FILES['files']['name'][$i]))
Change files to files[]. You can read about more here.
Suggestion
Move this line $this->load->library('upload',$config) out of the loop, because each iteration CI will try to load upload library which is already loaded. That may affect site's perfirmance. You can use initialize() function.

How do you upload image into database in Code igniter?

I've been trying to upload an image to my database (Note: I'm using Codeigniter 3) but every time I try to upload the image to the database it doesn't store it's filename and the image itself and only stores 1 bit in BLOB var type.
$photo = file_get_contents($_FILES['image']['tmp_name];
this->db->select('*')
[...]
if(empty($response){
$data['entry_phone_no'] = $this->input->post('phone_no');
$data['entry_email'] = $this->input->post('email');
$data['entry_firstname'] = $this->input->post('first_name');
$data['entry_lastname'] = $this->input->post('last_name');
$data['entry_photo'] = $photo;
$data['entry_photo_name'] = $photo;
In my model.php I have the setup above and it saves the other data (the phone num, email etc). I know I am missing some code at the "$photo" part but can anyone please point it out?
You can upload the image on folder called "Uploads" and save that filename into database as below:
Views.php:
<input class="my-set_3" type="file" name="chatbot_profile" id="chatbot_profile" required>
Controller.php:
if (!empty($_FILES['chatbot_profile']['name']))
{
$config['upload_path'] = './uploads';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1000000;
$config['file_name'] = time();
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('chatbot_profile'))
{
$error = array('error' => $this->upload->display_errors());
}
else
{
$data = array('upload_data' => $this->upload->data());
$file_name = $data['upload_data']['file_name'] ;
// Store this filename into database
// Your database code will be placed here
// OR call model mathod from here
}
}
Note: uploads folder will created by us and outside the application
folder.

Codeigniter image resize before upload

I am trying to upload multiple images in Codeigniter and reduce the size of each image.
here is my view
<?php echo form_open_multipart('main_controller/do_insert');?>
<div id="mainDiv">
<div class='group'>
<div><input type="text" name="name[]"/></div>
<div><input type="file" name="img[]"/></div>
</div>
</div>
<input type="button" id="add an entry">
<input type="submit" value="save all"/>
<?php from_close();?>
and my javascript is look like
<script>
function add(x)
{
var str1="<div><input type='text' name='name"+x+"'/></div>"
var str2="<div><input type='file' name='img"+x+"'/></div>"
var str3="<input type='button' value='add an entry' onClick='add(x+1)'>";
$("#mainDiv").append(str1+str2+str3);
}
</script>
here is my controller
function do_insert{
while($i<=$counter) /*conter have value of total number for images just ignore*/
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($userfileName))
{
echo "error".count;
}
else
{
$data = array('upload_data' => $this->upload->data());
$img=$data['upload_data']['file_name']; /*for geting uploaded image name*/
$config['image_library'] = 'gd2';
$config['source_image'] = './images/'.$img;
$config['new_image'] = './images/';
$config['maintain_ratio'] = TRUE;
$config['width'] = 640;
$config['height'] = 480;
$this->load->library('image_lib', $config);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
else
{
echo "success"; /*and some code here*/
}
}
}
}
my problem is that only the first image is getting re-sized remains kept as its original size.
And the image is resized after once uploaded. I think this is not a proper way now
Is there any alternative way to resize the image? it may be better if resize before doing the upload.
I have solved the problem resizing first image by making changes in my controller as `
$this->load->library('image_lib');
while($i<=$counter) /*conter have value of total number for images just ignore*/
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload($userfileName))
{
echo "error".count;
}
else
{
$image_data = $this->upload->data();
$configer = array(
'image_library' => 'gd2',
'source_image' => $image_data['full_path'],
'maintain_ratio' => TRUE,
'width' => 250,
'height' => 250,
);
$this->image_lib->clear();
$this->image_lib->initialize($configer);
$this->image_lib->resize();
}
}
I solved image resize before upload image in codeigniter use this simple code.
image.php
<form id="thumb_form" enctype="multipart/form-data" method="post">
<div style="margin-bottom: 5px;">
<label>Choose Image File</label>
<input id="image" name="image" type="file" class="form-control"/>
</div>
<div>
<input type="submit" class="btn btn-primary" name="add_video" id="add_video" value="Submit">
</div>
</form>
//ajax call write here
ajax call or script
<script>
$("form#thumb_form").submit(function(event)
{
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url : "<?php echo site_url('Welcome/add_image_thumb');?>",
type : "POST",
data: formData,
contentType: false,
processData: false,
dataType:"JSON",
success : function(result)
{
alert(result);
}
});
});
Welcome.php
public function add_image_thumb()
{
if($_FILES['image']['name']=='')
{
$data['file_err']='please choose image';
}
else
{
$data = $_FILES['image']['name'];
$config['image_library'] = 'gd2';
$config['source_image'] = $_FILES['image']['tmp_name'];
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['width'] = 300;
$config['height'] = 300;
$config['new_image'] = 'asstes/thumb/' . $data;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$img = '<img src="' . base_url() . 'asstes/thumb/' . $data . '">';
echo json_encode(array('img' => $img));
}
}
//Here is my upload controller and really works in local and server
//load you image_lib to your config
$config = array(
'upload_path' => './upload/',
'log_threshold' => 1,
'allowed_types' => 'jpg|png|jpeg|gif|JPEG|JPG|PNG',
'max_size' => 10000,
'max_width'=>0,
'overwrite' => false
);
for($i = 1 ; $i <=8 ; $i++) {
$upload = 'upload'.$i; //set var in upload
if(!empty($upload)){
$this->load->library('upload', $config);
$this->upload->do_upload('upload'.$i);
$upload_data = $this->upload->data();
$file_name = $upload_data['file_name'];
// process resize image before upload
$configer = array(
'image_library' => 'gd2',
'source_image' => $upload_data['full_path'],
'create_thumb' => FALSE,//tell the CI do not create thumbnail on image
'maintain_ratio' => TRUE,
'quality' => '40%', //tell CI to reduce the image quality and affect the image size
'width' => 640,//new size of image
'height' => 480,//new size of image
);
$this->image_lib->clear();
$this->image_lib->initialize($configer);
$this->image_lib->resize();
}
}

CodeIgniter Image Upload - can't get error message to show

This is my upload model
function upload_avatar()
{
$id = $this->tank_auth->get_user_id();
//config upload parameters and upload image
$config = array(
'allowed_types' => 'jpeg|jpg|png',
'upload_path' => $this->upload_path,
'max_size' => 2048,
'encrypt_name' => TRUE,
'overwrite' => FALSE,
);
$this->load->library('upload', $config);
$this->upload->do_upload();
//get upload data, config, resize uploaded image, save in avatars subfolder
$image_data = $this->upload->data();
if ($image_data['file_size'] < 2048) {
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->upload_path . '/avatars',
'maintain_ratio' => TRUE,
'width' => 125,
'height' => 125
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
//only burn avatar path to user_profiles table if no upload errors
if (!$this->upload->display_errors()) {
$data = array('avatar' => base_url() . 'images/avatars/' . $image_data['file_name']);
$this->db->where('id', $id);
$this->db->update('user_profiles', $data);
}
//delete the original file from server
$this->load->helper('file');
unlink($image_data['full_path']);
} else {
echo $this->upload->display_errors();
}
}
I can't get the error message to echo straight to the browser when I try uploading a file > 2MB.
To be fair, CI ignores this large file, and uploads correctly when a file is < 2MB.
The only thing is that I can't get the error message to show on the front-end to give the suer some feedback.
Any ideas what's wrong here?
$config['upload_path'] = 'uploads/category/'.$id.'/';
//echo $file_name;die;
//echo $config['upload_path'];
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '2048';
$config['max_width'] = '1920';
$config['max_height'] = '1280';
$this->load->library('upload');
foreach ($_FILES as $key => $value) {
//print_r($key);
if (!empty($key['name'])) {
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)) {
// echo 'test';die;
// rmdir('uploads/category/'.$id);
$errors = $this->upload->display_errors();
flashMsg($errors);
}
}
}
try this!!
Is your post_max_size limit less than 2MB? (http://ca3.php.net/manual/en/ini.core.php#ini.post-max-size) If so the file may have been discarded before your code is invoked.
Update:
If you take out your function call in the else block, and just drop in an exit('too big'); are you able to see errors then? If so there may be an issue with how you're pasing the call off.

Categories