How to change image name in multiupload with CodeIgniter? - php

I want to change image names when uploading more than one image. I have tried to use this config but it doesn't work $config['file_name'] = $this->getRandomString(); So, I need help with this
function addProductPhotoGallery() {
if ($this->session->userdata('admin_login')) {
$this->load->model('admin/admin_model');
$gallery_photo = array();
$gallery_path = realpath(APPPATH . '../imgs/product_pic/');
$config1['upload_path'] = $gallery_path;
$config1['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
$config1['max_size'] = '2000';
$this->load->library('upload', $config1);
$this->upload->initialize($config1);
$thum_path = realpath(APPPATH . '../imgs/product_pic/thumbs');
$config = array(
'image_library' => 'gd2',
'source_image' => '',
'maintain_ratio' => TRUE,
'width' => 300,
'height' => 200,
'new_image' => $thum_path
);
$this->load->library('image_lib', $config);
///////////// for loop and code that upload photo /////////////////////
$i = 1;
foreach ($_FILES as $filey) {
if (isset($_FILES['file' . $i])) {
$config['file_name'] = $this->input->post('username').$this->getRandomString();
// $_FILES['file' . $i]['name'] = $this->input->post('username').$this->getRandomString();
if($this->upload->do_upload('file' . $i)){
$phot_data = $this->upload->data();
$gallery_photo[$i] = $phot_data['file_name'];
$config['source_image'] = $phot_data['full_path'];
$this->image_lib->initialize($config);
$this->image_lib->resize();
$i++;
}else{
break;
return false;
}
}
}
return serialize($gallery_photo);
} else {
redirect('civou/home');
}
}

Try to putting $this->image_lib->clear()
after $this->image_lib->resize() so that on the next loop the/a new $config['file_name'] is used.

Related

How to restrict image size to a specific size when uploading in Codeigniter?

My controller function is
public function add() {
$blog_title = $this->input->post("qes_blog_title");
$description = htmlentities($_POST['qes_blog_description']);
$edit_status = $this->input->post("edit");
$filename = $blog_title . date('ymdhis');
if ($this->session->userdata('user_type') == "SA") {
$dirname = (dirname(dirname(dirname(__FILE__)))) .
'/uploads/blog/admin';
$usertype = "1";
} else {
$dirname = (dirname(dirname(dirname(__FILE__)))) . '/uploads/blog/'
. $this->session->userdata('user_id');
$usertype = "0";
}
if (!file_exists($dirname)) {
mkdir($dirname, 0777, true);
}
$config['upload_path'] = $dirname;
$config['file_name'] = $filename;
$config['allowed_types'] = 'jpeg|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload("qes_blog_image")) {
//print_r($this->upload->display_errors());
$data = array(
'qes_blog_title' => $blog_title,
'qes_blog_description' => $description,
'qes_vendor_id' => $this->session->userdata('user_id'),
'qes_user_type' => $usertype,
'qes_created_at' => date('Y-m-d H:i:s')
);
} else {
if ($edit_status) {
$condition = array(
'qes_vendor_blog_id' => $edit_status
);
$categoryDetails = $this->common_model->get_row($condition, $this->tablename);
if ($categoryDetails->qes_category_image != NULL) {
if ($this->session->userdata('user_type') == "SA") {
unlink((dirname(dirname(dirname(__FILE__)))) . '/uploads/blog/admin/' . $categoryDetails->qes_blog_image);
} else {
unlink((dirname(dirname(dirname(__FILE__)))) . '/uploads/blog/' . $categoryDetails->qes_vendor_id . "/" . $categoryDetails->qes_blog_image);
}
}
}
$uploqes_data = $this->upload->data();
$uploqes_filename = $uploqes_data['file_name'];
$data = array(
'qes_blog_title' => $blog_title,
'qes_blog_description' => $description,
'qes_vendor_id' => $this->session->userdata('user_id'),
'qes_user_type' => $usertype,
'qes_blog_image' => $uploqes_filename,
'qes_created_at' => date('Y-m-d H:i:s')
);
}
$condition = array(
'qes_blog_title' => $blog_title
);
$blog_details = $this->common_model->get_row($condition, $this->tablename);
if ($edit_status) {
if (count($blog_details) > 0) {
if ($blog_details->qes_blog_title == $blog_title) {
$condition = array(
'qes_vendor_blog_id' => $edit_status
);
$result = $this->common_model->update_row($data, $condition, $this->tablename);
$status = 'Blog "<b>' . $blog_title . '</b>" Successfully Updated';
} else {
$htm = "0";
$result = "0";
$status = "0";
}
} else {
$condition = array(
'qes_vendor_blog_id' => $edit_status
);
$result = $this->common_model->update_row($data, $condition, $this->tablename);
$status = 'Blog "<b>' . $blog_title . '</b>" Successfully Updated';
}
} else {
if (count($blog_details) > 0) {
if ($blog_details->qes_blog_title == $blog_title) {
$htm = "0";
$result = "0";
$status = "0";
} else {
$result = $this->common_model->insert_data($this->tablename, $data);
$status = 'Blog "<b>' . $blog_title . '</b>" Successfully Created';
}
} else {
$result = $this->common_model->insert_data($this->tablename, $data);
$status = 'Blog "<b>' . $blog_title . '</b>" Successfully Created';
}
}
if ($result) {
$htm = $result;
$this->session->set_flashdata('success_msg', $status);
} else {
$htm = '0';
$this->session->set_flashdata('success_msg', 'Error While Creating Parent');
}
echo $htm;
}
I'm a beginner in Codeigniter.
How to restrict the size of image while uploading. Only images of specific size can be uploaded. The above is the controller function to add blog. How to specify the size in the above code. How to keep a condition like "upload image only of the specified size" while uploading image in Codeigniter?
Please refer this code, this may help you..thanks!
$file_name = '';
$error = '';
if ($_FILES['image']['name'] != '') {
$config['upload_path'] = 'uploads/blog/main/';
$config['allowed_types'] = 'jpg|png|jpeg';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image')) {
$error = $this->upload->display_errors();
} else {
$data = array('upload_data' => $this->upload->data());
$file_name = $data['upload_data']['file_name'];
$config['source_image'] = 'uploads/blog/main/' . $file_name;
$config['new_image'] = 'uploads/blog/thumb/' . $file_name;
$config['width'] = 172;
$config['height'] = 122;
$config['maintain_ratio'] = FALSE;
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
if ($data['upload_data']['image_height'] > $this->main_height || $data['upload_data']['image_width'] > $this->main_width) {
$config['image_library'] = 'gd2';
$config['source_image'] = 'uploads/blog/main/' . $file_name;
$config['new_image'] = 'uploads/blog/main/' . $file_name;
$config['width'] = $this->main_width;
$config['height'] = $this->main_height;
$config['maintain_ratio'] = FALSE;
$this->image_lib->initialize($config);
$this->image_lib->resize();
}
}
}
instead of copy pasting the raw code , let me give you the sample for each actions you like to do with image uploading in php. so that you can make us of any of below to achieve your result.
1. To check if image is received or not. use,
if(isset($_FILES["image"])){
// image received
} else {
// image not received
}
2. To check if the image is properly uploaded or not. use,
if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) {
// error
die("Upload failed with error code " . $_FILES['image']['error']);
} else {
// no error
}
3. To check if your image is in valid format. use,
$info = getimagesize($_FILES['image']['tmp_name']);
if ($info === FALSE) {
//Unable to determine image type of uploaded file
}
if (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
// File received is not in valid format
}
4. to get size of the image, use above method and as well as,
$width = $info[0];
$height = $info[1];
4.1 To check if image is square,
if($width!=$height) {
//Image is not square
}
4.1 To check minimum pixel image width
if($width<50) { // Image width should be atleast 50 pixel }
you can play with conditional statement to receive the required image size you are looking for.
To upload the image ( not exactly need to be in below format, modify it according to the need ),
$imagename=($_FILES["image"]["tmp_name"]);
$filename = $_FILES['image']['name'];
$temp = explode(".",$_FILES["image"]["name"]);
$filename = rand(1,99999).'.'.end($temp);
move_uploaded_file($_FILES["image"]["tmp_name"], "../your_path/" . $filename);
Edit
If you want to restrict the image size to a specific width and height, set both minimum and maximum of width and height to the same value in the config. For eg. to restrict image size to 1024x768, you can set the preferences in config as follows
$config['min_width'] = '1024'; // restrict width to 1024px
$config['min_height'] = '768'; // restrict height to 768px
$config['max_width'] = '1024'; // restrict width to 1024px
$config['max_height'] = '768'; // restrict height to 768px
$this->load->library('upload', $config); // pass the config when loading the library
If you use autoload, pass the config to the initialize method.
$this->upload->initialize($config);
Side note:
I see that you are passing the config while loading the library and then also initializing. This is redundant. initialize method is used if you are using the autoload feature.

Picture resize function when uploading in CodeIgniter not working

I made a function on the CodeIgniter framework so users can upload pictures of products to a product page. The thing is I want pictures to be resized to the width and height I want it to be. Since I added the image lib resize function in my upload function nothing is working anymore.
This is my upload function:
public function upload() {
$this->load->library('upload');
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('product_form', $error);
} else {
$file_data = $this->upload->data();
$this->load->library('image_lib');
foreach ($results as $row) {
$config['image_library'] = 'gd2';
$config['source_image'] = './upload/' . $file_data["file_name"];
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 75;
$config['height'] = 50;
$this->image_lib->clear();
$this->image_lib->initialize($config);
$this->image_lib->resize();
}
$this->db->insert('products', array(
'product_foto' => $file_data['file_name'],
'product_naam' => $this->input->post('product_naam'),
'product_beschrijving' => $this->input->post('product_beschrijving'),
'product_categorie' => $this->input->post('product_categorie'),
'ophaal_plaats' => $this->input->post('ophaal_plaats'),
'date_created' => date('Y-m-d'),
'date_updated' => date('Y-m-d')
));
$data['img'] = base_url() . '/upload/' . $file_data['file_name'];
header('location:https://kadokado-ferran10.c9users.io/Product/');
}
What am I doing wrong?
It works for me :
if(!empty($_FILES['image_field']['name']))
{
$config['upload_path'] = './image_folder';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '262144';
$config['overwrite'] = FALSE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('image_field'))
{
echo "Not Upload";
echo $this->upload->display_errors();
// $this->session->set_flashdata('error','<div class="alert alert-warning">Something went wrong...try again...</div>');
//redirect('Controller/function_name');
}
else
{
$image_data = $this->upload->data();
$config1['image_library'] = 'gd2';
$config1['source_image'] = './image_folder/'.$image_data['file_name'];
$config1['maintain_ratio'] = TRUE;
$config1['quality'] = '50%';
$config1['width'] = 50;
$config1['height'] = 50;
$this->load->library('image_lib', $config1);
$this->image_lib->resize();
if ( ! $this->image_lib->resize())
{
echo $this->image_lib->display_errors();
}
echo $image_data['file_name'];
exit;
// save to database
}
}

upload 2 or more image with different field name and different input in codeigniter

i want to upload several image with different input and different field name for each image. i actually try to separate it in two different method like this
public function tambahketua(){
if(isset($_POST["reg"]))
{
$config['upload_path'] = './asset/img/foto/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|xml|docx|GIF|JPG|PNG|JPEG|PDF|DOC|XML|DOCX|xls|xlsx';
$config['max_size'] = 200048;
$config['file_name'] = $this->input->post("namaketua");
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('attachment'))//ini name di input choose file
{
}
else
{
$datas = $this->upload->data();
$edit['image_library'] = 'gd2';
$edit['source_image'] = './asset/img/foto/'.$datas['file_name'];
$edit['create_thumb'] = TRUE;
$edit['maintain_ratio'] = TRUE;
$edit['height'] = 600;
$this->load->library('image_lib', $edit);
$this->image_lib->resize();
$edit_file = explode('.', $datas['file_name']);
$data['foto'] = $edit_file[0].'_thumb.'.$edit_file[1];
unlink($config['upload_path'].$datas['file_name']);
}
$a = $this->miniatur_model->insertPeserta($data);
if($a){
$this->tambahanggota1();
}
else{
echo "failed";
}
}
$this->load->view('pendaftaran');
}
public function tambahanggota1(){
if(isset($_POST["reg"]))
{
$config['upload_path'] = './asset/img/foto/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|xml|docx|GIF|JPG|PNG|JPEG|PDF|DOC|XML|DOCX|xls|xlsx';
$config['max_size'] = 200048;
$config['file_name'] = $this->input->post("namaanggota1");
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('fotoktmanggota1'))//ini name di input choose file
{
}
else
{
$datas = $this->upload->data();
$edit['image_library'] = 'gd2';
$edit['source_image'] = './asset/img/foto/'.$datas['file_name'];
$edit['create_thumb'] = TRUE;
$edit['maintain_ratio'] = TRUE;
$edit['height'] = 600;
$this->load->library('image_lib', $edit);
$this->image_lib->resize();
$edit_file = explode('.', $datas['file_name']);
$data['foto'] = $edit_file[0].'_thumb.'.$edit_file[1];
unlink($config['upload_path'].$datas['file_name']);
}
$a = $this->miniatur_model->insertPeserta($data);
if($a){
echo "success";
}
else{
echo "failed";
}
}
$this->load->view('pendaftaran');
}
and so far i could only write both of the image name into my database, but only the first one uploaded into my folder.
and this is my view
<input type="file" id="attachment" name="attachment">
<input type="file" id="fotoktmanggota1" name="fotoktmanggota1">
and for some reason i cant change the name of my files into array like name="attachment[]"
I have minimized your extra code. Try this and do your own magic if I missed something.
function tambahketua() {
if (isset($_POST["reg"])) {
$config['upload_path'] = './asset/img/foto/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|doc|xml|docx|GIF|JPG|PNG|JPEG|PDF|DOC|XML|DOCX|xls|xlsx';
$config['max_size'] = 200048;
$this->upload->initialize($config);
if (!$this->upload->do_upload('attachment')) {
$error = array('error' => $this->upload->display_errors());
// var_dump($error);
} else {
$fileData = $this->upload->data();
$data['foto'] = $fileData['file_name'];
$this->doResize($fileData['file_name']);
}
$insertedFirstImage = $this->miniatur_model->insertPeserta($data);
if ($insertedFirstImage) {
// Upload Second Image on Success
if (!$this->upload->do_upload('fotoktmanggota1')) {
$error = array('error' => $this->upload->display_errors());
} else {
$fileData = $this->upload->data();
$data['foto'] = $fileData['file_name'];
$this->doResize($fileData['file_name']);
}
$insertedSecondImage = $this->miniatur_model->insertPeserta($data);
/*---------------------------------------*/
} else{
echo "Image insertion Failed in database";
}
}
$this->load->view('pendaftaran');
}
function doResize($filename) {
$sourcePath = './asset/img/foto/' . $filename;
$targetPath = './asset/img/foto/thumb/thumb_' . $filename;
$config_manip = array(
'image_library' => 'gd2',
'source_image' => $sourcePath,
'new_image' => $targetPath,
'maintain_ratio' => true,
'width' => 150,
'height' => 150
);
$this->image_lib->initialize($config_manip);
$this->load->library('image_lib', $config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
exit;
}
// clear //
// $this->image_lib->clear();
}

Image Resizing not function in codeigniter

I have an upload_images function
$config['upload_path'] = './uploads/individual_stands/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = FALSE;
This config is passed to upload_images function.
function upload_images($config, $files, $name) {
if (!file_exists($config['upload_path'])) {
mkdir($config['upload_path'], 0777, true);
}
$this->load->library('upload', $config);
$filesCount = count($files[$name]['name']);
for ($i = 0; $i < $filesCount; $i++) {
$_FILES = array();
$_FILES['image']['name'] = $files[$name]['name'][$i];
$_FILES['image']['type'] = $files[$name]['type'][$i];
$_FILES['image']['tmp_name'] = $files[$name]['tmp_name'][$i];
$_FILES['image']['error'] = $files[$name]['error'][$i];
$_FILES['image']['size'] = $files[$name]['size'][$i];
$this->upload->initialize($config);
if ($this->upload->do_upload('image')) {
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
image_resizing($config['upload_path'] . $fileData['file_name'], $fileData['file_name'] . '_250x250', $config['upload_path'], '250', TRUE, '250');
}
}
if (!empty($uploadData)) {
$data = array(
'status' => 'success',
'images' => $uploadData
);
} else {
$data = array(
'status' => 'error',
'error' => $this->upload->display_errors()
);
}
return $data;
}
And I have a helper function called 'image_resizing'. I am passing the correct parameters inside my helper function but neither the thumb directory is being created, nor the images are being resized.
function image_resizing($imageObj, $fileName, $path = '', $width = 0, $create_thumb = TRUE, $height = 0) {
$newdir = $path. 'thumb/';
if (!file_exists($newdir)) {
mkdir($path, 0777, true);
}
$CI = & get_instance();
$config['image_library'] = 'gd2';
$config['source_image'] = $imageObj;
$config['new_image'] = $path . 'thumb/' . $fileName;
$config['create_thumb'] = $create_thumb;
$config['maintain_ratio'] = TRUE;
if ($width != 0)
$config['width'] = $width;
if ($height != 0)
$config['height'] = $height;
$CI->load->library('image_lib', $config);
$CI->image_lib->initialize($config);
if (!$CI->image_lib->resize()) {
return FALSE;
} else {
return TRUE;
}
}

Codeigniter thumbnail array not working

Im doing multiple file uploading, which is working fine.
im getting both images but the other image which is thumnail not getting their given path and also not changing in to thumb size.
I have just issues with thumbnail in "thumbnail creation start" area i hope.
check my array and let me know my mistake.
controller codes
public function addimage($room_id)
{
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++)
{
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name']; // get file names for first file
//thumbnail creation start
$config1['image_library'] = 'gd2';
$config1['source_image'] = $image['full_path'];
$config1['create_thumb'] = TRUE;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config1['maintain_ratio'] = TRUE;
$config1['upload_path'] = './uploads/thumbs/';
$config1['width'] = 150;
$config1['height'] = 150;
$this->load->library('image_lib', $config1);
$this->image_lib->resize();
$this->upload->do_upload();
$data = $this->upload->data();
$name_array1[] = $data['file_name']; // file names for thumb
//thumbnail creation end
}
$names= implode(',', $name_array);
$names2= implode(',', $name_array1);
//print_r($names);
$options = array(
'id' => '0',
'org_image' => $names,
'thumbnail' => $names2,
'room_id' => $room_id,
'created' => '1',
'status' => '1'
);
$this->rooms_model->room_images_insert($options);
redirect('/admin/rooms', 'location');
} //end of function
Replace
$config1['source_image'] = $image['full_path'];
To
$config1['source_image'] = $data['full_path'];
Also remove the following commented lines
$this->image_lib->resize();
//$this->upload->do_upload();
//$data = $this->upload->data();
After you do config for your image i.e., setting your image attributes then you should clear and initizliae the image_lib to get effect.
$this->image_lib->clear();
$this->image_lib->initialize($config);
$this->image_lib->resize();
Note :
Make sure that you need it for $config or $config1
Make sure that you have the source_image path right
public function addimage($room_id)
{
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++)
{
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name']; // get file names for first file
//thumbnail creation start
$config1['image_library'] = 'gd2';
$config1['source_image'] = $data['full_path'];
$config1['create_thumb'] = TRUE;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config1['maintain_ratio'] = TRUE;
$config1['upload_path'] = './uploads/thumbs/';
$config1['width'] = 500;
$config1['height'] = 150;
$this->load->library('image_lib', $config1);
$this->image_lib->clear();
$this->image_lib->initialize($config1);
$this->image_lib->resize();
$name_array1[] = $data['file_name']; // get file names for thumb file
//thumbnail creation end
}
$names= implode(',', $name_array);
$names2= implode(',', $name_array1);
//print_r($names);
$options = array(
'id' => '0',
'org_image' => $names,
'thumbnail' => $names2,
'room_id' => $room_id,
'created' => '1',
'status' => '1'
);
$this->rooms_model->room_images_insert($options);
redirect('/admin/rooms', 'location');
} //end of function

Categories