Codeigniter image lib not resizing multiple images at once - codeigniter

I am trying to resize multiple images at once in my foreach loop but does not do it. It only resizes some of them per page.
Question how can I make sure it resizes the multiple images at once in my foreach loop on index()
As you can see it only resizes some of them the filemanager code is run/loaded ajax
<?php
class Filemanager extends MX_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('pagination');
}
public function index()
{
$data['resize_error'] ='';
$input_get_directory = $this->input->get('directory');
$input_get_page = $this->input->get('page');
$input_get_filter = $this->input->get('filter_name');
$input_get_target = $this->input->get('target');
$input_get_thumb = $this->input->get('thumb');
if (isset($input_get_filter)) {
$filter_name = $input_get_filter;
} else {
$filter_name = null;
}
// Make sure we have the correct directory
if (isset($input_get_directory)) {
$directory = FCPATH . 'image/catalog/' . $input_get_directory;
} else {
// Do not add extra tralier slash at end /
$directory = FCPATH . 'image/catalog';
}
if (isset($input_get_page)) {
$page = $input_get_page;
} else {
$page = 1;
}
$data['images'] = array();
// Get directories
$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);
if (!$directories) {
$directories = array();
}
// Get files
$files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
if (!$files) {
$files = array();
}
// Merge directories and files
$images = array_merge($directories, $files);
// Get total number of files and directories
$image_total = count($images);
$per_page = 8;
$segment = $this->input->get('per_page');
$segment += $per_page;
foreach ($images as $key => $image) {
if ($key < $segment && $key >= $segment - $per_page) {
$name = str_split(basename($image), 18);
if (is_dir($image)) {
$url = '';
if (isset($input_get_target)) {
$url .= '&target=' . $input_get_target;
}
if (isset($input_get_thumb)) {
$url .= '&thumb=' . $input_get_thumb;
}
$data['images'][] = array(
'thumb' => '',
'name' => implode(' ', $name),
'type' => 'directory',
'path' => utf8_substr($image, utf8_strlen(FCPATH . 'image/')),
'href' => site_url('admin/common/filemanager') . '/?&directory=' . utf8_substr($image, utf8_strlen(FCPATH . 'image/' . 'catalog/')) . $url
);
} elseif (is_file($image)) {
// Resize function here
$data['images'][] = array(
'thumb' => $this->resize($image),
'name' => implode(' ', $name),
'type' => 'image',
'test' => '',
'path' => utf8_substr($image, utf8_strlen(FCPATH . 'image/')),
'href' => base_url() . 'image/' . utf8_substr($image, utf8_strlen(FCPATH . 'image/'))
);
}
}
}
$this->load->view('common/filemanager_view', $data);
}
public function resize($filename) {
$this->load->library('image_lib');
$width = 100;
$height = 100;
$old_filename = substr($filename, strlen(FCPATH . 'image/'));
$extension = pathinfo($old_filename, PATHINFO_EXTENSION);
$new_image = substr($old_filename, 0, strrpos($old_filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
$config['image_library'] = 'gd2';
$config['source_image'] = $filename;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['width'] = $width;
$config['height'] = $height;
$config['new_image'] = FCPATH . 'image/cache/' . $new_image;
$this->image_lib->clear();
$this->image_lib->initialize($config);
$this->image_lib->resize();
return base_url('image/cache/') . $new_image;
}
}
This function below is called in the foreach loop on index
public function resize($filename) {
$this->load->library('image_lib');
$width = 100;
$height = 100;
$old_filename = substr($filename, strlen(FCPATH . 'image/'));
$extension = pathinfo($old_filename, PATHINFO_EXTENSION);
$new_image = substr($old_filename, 0, strrpos($old_filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
$config['image_library'] = 'gd2';
$config['source_image'] = $filename;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['width'] = $width;
$config['height'] = $height;
$config['new_image'] = FCPATH . 'image/cache/' . $new_image;
$this->image_lib->clear();
$this->image_lib->initialize($config);
$this->image_lib->resize();
return base_url('image/cache/') . $new_image;
}
Just the view for any one who wants it
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<div class="btn-toolbar mb-3" role="toolbar" aria-label="Toolbar with button groups">
<div class="btn-group mr-2" role="group" aria-label="First group">
<a class="btn btn-dark" href="<?php echo $parent;?>" data-toggle="tooltip" data-placement="top" title="<?php echo $button_parent; ?>" id="button-parent" class="btn btn-default"><i class="fa fa-level-up"></i></a>
<button type="button" data-toggle="tooltip" data-placement="top" title="<?php echo $button_upload; ?>" id="button-upload" class="btn btn-primary"><i class="fa fa-upload"></i></button>
<button type="button" data-toggle="tooltip" data-placement="top" title="<?php echo $button_folder; ?>" id="button-folder" class="btn btn-dark"><i class="fa fa-folder"></i></button>
<button type="button" data-toggle="tooltip" data-placement="top" title="<?php echo $button_delete; ?>" id="button-delete" class="btn btn-danger"><i class="fa fa-trash-o"></i></button>
</div>
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-secondary" type="button"><i class="fa fa-search" aria-hidden="true"></i></button>
</span>
<input type="text" class="form-control" placeholder="Search for..." aria-label="Search for...">
</div>
</div>
</div>
<div class="modal-header justify-content-center">
<ol class="breadcrumb">
<?php foreach ($breadcrumbs as $breadcrumb) { ?>
<li class="breadcrumb-item"><?php echo $breadcrumb['text']; ?></li>
<?php } ?>
</ol>
</div>
<div class="modal-body">
<!--
<div class="row">
<div class="col-sm-5">
<i class="fa fa-refresh"></i>
</div>
</div>
-->
<?php foreach (array_chunk($images, 4) as $image) { ?>
<div class="row">
<?php foreach ($image as $image) { ?>
<div class="col-sm-3 text-center">
<?php if ($image['type'] == 'directory') { ?>
<div class="text-center"><i class="fa fa-folder fa-5x"></i></div>
<label>
<input type="checkbox" name="path[]" value="<?php echo $image['path']; ?>" />
<?php echo $image['name']; ?></label>
<?php } ?>
<?php if ($image['type'] == 'image') { ?>
<a href="<?php echo $image['href']; ?>" class="thumbnail">
<?php echo $image['thumb']; ?></a>
<label>
<input type="hidden" name="cache[]" value="<?php echo $image['cache']; ?>" />
<input type="checkbox" name="path[]" value="<?php echo $image['path']; ?>" />
<?php echo $image['name']; ?></label>
<?php } ?>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<div class="modal-footer justify-content-center">
<?php echo $pagination; ?>
</div>
</div>
</div>
<script type="text/javascript"><!--
$('a.thumbnail').on('click', function(e) {
e.preventDefault();
<?php if ($thumb) { ?>
$('#<?php echo $thumb; ?>').find('img').attr('src', $(this).find('img').attr('src'));
<?php } ?>
<?php if ($target) { ?>
$('#<?php echo $target; ?>').attr('value', $(this).parent().find('input').attr('value'));
<?php } else { ?>
var range, sel = document.getSelection();
if (sel.rangeCount) {
var img = document.createElement('img');
img.src = $(this).attr('href');
range = sel.getRangeAt(0);
range.insertNode(img);
}
<?php } ?>
$('#modal-image').modal('hide');
});
$('a.directory').on('click', function(e) {
e.preventDefault();
$('#modal-image').load($(this).attr('href'));
});
$('.pagination a').on('click', function(e) {
e.preventDefault();
$('#modal-image').load($(this).attr('href'));
});
$('.breadcrumb-item a').on('click', function(e) {
e.preventDefault();
$('#modal-image').load($(this).attr('href'));
});
$('#button-parent').on('click', function(e) {
e.preventDefault();
$('#modal-image').load($(this).attr('href'));
});
$('#button-refresh').on('click', function(e) {
e.preventDefault();
$('#modal-image').load($(this).attr('href'));
});
$('input[name=\'search\']').on('keydown', function(e) {
if (e.which == 13) {
$('#button-search').trigger('click');
}
});
$('#button-search').on('click', function(e) {
var url = 'admin/common/filemanager?&directory=<?php echo $directory; ?>';
var filter_name = $('input[name=\'search\']').val();
if (filter_name) {
url += '&filter_name=' + encodeURIComponent(filter_name);
}
<?php if ($thumb) { ?>
url += '&thumb=' + '<?php echo $thumb; ?>';
<?php } ?>
<?php if ($target) { ?>
url += '?target=' + '<?php echo $target; ?>';
<?php } ?>
$('#modal-image').load(url);
});
//--></script>
<script type="text/javascript"><!--
$('#button-upload').on('click', function() {
$('#form-upload').remove();
$('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" value="" /></form>');
$('#form-upload input[name=\'file\']').trigger('click');
if (typeof timer != 'undefined') {
clearInterval(timer);
}
timer = setInterval(function() {
if ($('#form-upload input[name=\'file\']').val() != '') {
clearInterval(timer);
$.ajax({
url: '<?php echo base_url('admin/common/filemanager/upload?');?>directory=<?php echo $directory; ?>',
type: 'post',
dataType: 'json',
data: new FormData($('#form-upload')[0]),
cache: false,
contentType: false,
processData: false,
beforeSend: function() {
$('#button-upload i').replaceWith('<i class="fa fa-circle-o-notch fa-spin"></i>');
$('#button-upload').prop('disabled', true);
},
complete: function() {
$('#button-upload i').replaceWith('<i class="fa fa-upload"></i>');
$('#button-upload').prop('disabled', false);
},
success: function(json) {
if (json['error']) {
alert(json['error']);
}
if (json['success']) {
alert(json['success']);
$('#button-refresh').trigger('click');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
}, 500);
});
$('#button-folder').popover({
html: true,
placement: 'bottom',
trigger: 'click',
title: 'New Folder',
content: function() {
html = '<div class="input-group">';
html += ' <input type="text" name="folder" value="" placeholder="New Folder" class="form-control">';
html += ' <span class="input-group-btn"><button type="button" title="" id="button-create" class="btn btn-primary"><i class="fa fa-plus-circle"></i></button></span>';
html += '</div>';
return html;
}
});
$('#button-folder').on('shown.bs.popover', function() {
$('#button-create').on('click', function() {
$.ajax({
url: 'admin/common/filemanager/folder?directory=<?php echo $directory; ?>',
type: 'post',
dataType: 'json',
data: 'folder=' + encodeURIComponent($('input[name=\'folder\']').val()),
beforeSend: function() {
$('#button-create').prop('disabled', true);
},
complete: function() {
$('#button-create').prop('disabled', false);
},
success: function(json) {
if (json['error']) {
alert(json['error']);
}
if (json['success']) {
alert(json['success']);
$('#button-refresh').trigger('click');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
});
$('#modal-image #button-delete').on('click', function(e) {
if (confirm('Are You Sure')) {
$.ajax({
url: 'admin/common/filemanager/delete/',
type: 'post',
dataType: 'json',
data: {
path: $('input[name^=\'path\']:checked'),
cache: $('input[name^=\'cache\']').val()
},
beforeSend: function() {
$('#button-delete').prop('disabled', true);
},
complete: function() {
$('#button-delete').prop('disabled', false);
},
success: function(json) {
if (json['error']) {
alert(json['error']);
}
if (json['success']) {
alert(json['success']);
$('#button-refresh').trigger('click');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
});
//--></script>

Try adding an error handler on resize() to see if there's an error that's preventing an image from getting resized:
$this->image_lib->clear();
$this->image_lib->initialize($config);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
Update
It seems the segment is not initialized correctly
$segment = $this->input->get('per_page');
Instead try
$segment = $this->input->get('page') * $this->input->get('per_page');

Solution
I have working solution now
I have had to make a check of the directory
if (!is_dir(DIR_IMAGE . 'cache/' . $new_image)) {
if ($this->input->get('directory')) {
#mkdir(DIR_IMAGE . 'cache/catalog/' . $this->input->get('directory') .'/', 0777, true);
} else {
#mkdir(DIR_IMAGE . 'cache/catalog/', 0777, true);
}
}
And also use use a if file exists for resize check and also codeigniter img() helper function helped also.
Full Controller
<?php
class Filemanager extends MX_Controller {
public function __construct()
{
parent::__construct();
$this->load->library('pagination');
$this->load->library('image_lib');
$this->load->helper('html');
define('DIR_IMAGE', FCPATH . 'image/');
}
public function index()
{
$data['resize_error'] ='';
$input_get_directory = $this->input->get('directory');
$input_get_page = $this->input->get('page');
$input_get_filter = $this->input->get('filter_name');
$input_get_target = $this->input->get('target');
$input_get_thumb = $this->input->get('thumb');
if (isset($input_get_filter)) {
$filter_name = $input_get_filter;
} else {
$filter_name = null;
}
// Make sure we have the correct directory
if (isset($input_get_directory)) {
$directory = FCPATH . 'image/catalog/' . $input_get_directory;
} else {
// Do not add extra tralier slash at end /
$directory = FCPATH . 'image/catalog';
}
if (isset($input_get_page)) {
$page = $input_get_page;
} else {
$page = 1;
}
$data['images'] = array();
// Get directories
$directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR);
if (!$directories) {
$directories = array();
}
// Get files
$files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
if (!$files) {
$files = array();
}
// Merge directories and files
$images = array_merge($directories, $files);
// Get total number of files and directories
$image_total = count($images);
$per_page = 8;
$segment = $this->input->get('per_page');
$segment += $per_page;
$this->load->model('admin/tool/image_model');
$this->load->helper('string');
foreach ($images as $key => $image) {
if ($key < $segment && $key >= $segment - $per_page) {
$name = basename(preg_replace("/\.[^.]+$/", "", $image));
if (is_dir($image)) {
$url = '';
if (isset($input_get_target)) {
$url .= '&target=' . $input_get_target;
}
if (isset($input_get_thumb)) {
$url .= '&thumb=' . $input_get_thumb;
}
$data['images'][] = array(
'thumb' => '',
'name' => $name,
'href' => '',
'type' => 'directory',
'path' => substr($image, strlen(FCPATH . 'image/')),
'href' => site_url('admin/common/filemanager/?&directory=' . substr($image, strlen(FCPATH . 'image/' . 'catalog/')) . $url)
);
} elseif (is_file($image)) {
$width = 100;
$height = 100;
$old_filename = substr($image, strlen(DIR_IMAGE));
$extension = pathinfo($old_filename, PATHINFO_EXTENSION);
$new_image = substr($old_filename, 0, strrpos($old_filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
if (!is_dir(DIR_IMAGE . 'cache/' . $new_image)) {
if ($this->input->get('directory')) {
#mkdir(DIR_IMAGE . 'cache/catalog/' . $this->input->get('directory') .'/', 0777, true);
} else {
#mkdir(DIR_IMAGE . 'cache/catalog/', 0777, true);
}
}
if (!file_exists(DIR_IMAGE . 'cache/' . $new_image)) {
$config = array(
'image_library' => 'gd2',
'source_image' => $image,
'create_thumb' => false,
'maintain_ratio' => false,
'width' => $width,
'height' => $height,
'overwrite' => true,
'new_image' => DIR_IMAGE . 'cache/' . $new_image
);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
}
$data['images'][] = array(
'type' => 'image',
'href' => '',
'thumb' => img('image/cache/'. $new_image),
'name' => (strlen($name) > 13) ? substr($name,0,10).'...' : $name,
'path' => substr($image, strlen(DIR_IMAGE))
);
}
}
}
$data['heading_title'] = "Image Manager";
$data['text_no_results'] = "No Results";
$data['text_confirm'] = "Are You Sure";
$data['entry_search'] = "Search..";
$data['entry_folder'] = "New Folder";
$data['button_parent'] = "Parent";
$data['button_refresh'] = "Refresh";
$data['button_upload'] = "Upload";
$data['button_folder'] = "New Folder";
$data['button_delete'] = "Delete";
$data['button_search'] = "Search";
if (isset($input_get_directory)) {
$data['directory'] = $input_get_directory;
} else {
$data['directory'] = '';
}
// Return the filter name
if (isset($input_get_filter)) {
$data['filter_name'] = $input_get_filter;
} else {
$data['filter_name'] = '';
}
// Return the target ID for the file manager to set the value
if (isset($input_get_target)) {
$data['target'] = $input_get_target;
} else {
$data['target'] = '';
}
// Return the thumbnail for the file manager to show a thumbnail
if (isset($input_get_thumb)) {
$data['thumb'] = $input_get_thumb;
} else {
$data['thumb'] = '';
}
// Parent
$url = '';
if (isset($input_get_directory)) {
$pos = strrpos($input_get_directory, '/');
if ($pos) {
$url .= '/?&directory=' . substr($input_get_directory, 0, $pos);
}
}
$data['parent'] = site_url('admin/common/filemanager' . $url);
// Refresh
$url = '';
if (isset($input_get_directory)) {
$url .= '/?&directory=' . $input_get_directory;
}
if (isset($input_get_target)) {
$url .= '&target=' . $input_get_target;
}
if (isset($input_get_thumb)) {
$url .= '&thumb=' . $input_get_thumb;
}
$data['refresh'] = site_url('admin/common/filemanager' . $url);
$url = '';
if (isset($input_get_directory)) {
$url .= '?&directory=' . $input_get_directory;
}
if (isset($input_get_filter)) {
$url .= '&filter_name=' . $input_get_filter;
}
if (isset($input_get_target)) {
$url .= '/?&target=' . $input_get_target;
}
if (isset($input_get_thumb)) {
$url .= '&thumb=' . $input_get_thumb;
}
$this->load->library('pagination');
$config['base_url'] = base_url('admin/common/filemanager' . $url);
$config['total_rows'] = $image_total;
$config['per_page'] = $per_page;
$config['page_query_string'] = TRUE;
$config['num_links'] = "16";
$config['full_tag_open'] = "<ul class='pagination'>";
$config['full_tag_close'] = "</ul>";
$config['num_tag_open'] = '<li>';
$config['num_tag_close'] = '</li>';
$config['cur_tag_open'] = "<li class='disabled'><li class='active'><a href='#'>";
$config['cur_tag_close'] = "<span class='sr-only'></span></a></li>";
$config['next_tag_open'] = "<li>";
$config['next_tagl_close'] = "</li>";
$config['prev_tag_open'] = "<li>";
$config['prev_tagl_close'] = "</li>";
$config['first_tag_open'] = "<li>";
$config['first_tagl_close'] = "</li>";
$config['last_tag_open'] = "<li>";
$config['last_tagl_close'] = "</li>";
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$this->load->view('common/filemanager_view', $data);
}
public function resize($filename) {
$this->load->library('image_lib');
//foreach ($filename as $key => $file) {}
$width = 100;
$height = 100;
$old_filename = substr($filename, strlen(FCPATH . 'image/'));
$extension = pathinfo($old_filename, PATHINFO_EXTENSION);
$new_image = substr($old_filename, 0, strrpos($old_filename, '.')) . '-' . $width . 'x' . $height . '.' . $extension;
$config['image_library'] = 'gd2';
$config['source_image'] = $filename;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['width'] = $width;
$config['height'] = $height;
$config['new_image'] = FCPATH . 'image/cache/' . $new_image;
$this->image_lib->clear();
$this->image_lib->initialize($config);
if (!$this->image_lib->resize()) {
return $this->image_lib->display_errors();
} else {
return base_url('image/cache/') . $new_image;
}
}
/**
* Codeigniter upload library with json and config_item
*/
public function upload()
{
$json = array();
$input_get_directory = $this->input->get('directory');
if (isset($input_get_directory)) {
$directory = 'image/catalog/' . $input_get_directory;
} else {
$directory = 'image/catalog';
}
$config['upload_path'] = './' . $directory . '/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5000;
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['overwrite'] = FALSE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$input_name = "file";
if ($this->upload->do_upload($input_name) == FALSE) {
$json['error'] = $this->upload->display_errors();
} else {
$file_data = $this->upload->data();
$json['success'] = "This file" . ' ' . $file_data['file_name'] . ' ' . "has been uploaded";
}
$this->output->set_content_type('Content-Type: application/json');
$this->output->set_output(json_encode($json));
}
public function folder()
{
$json = array();
$input_get_directory = $this->input->get('directory');
// Make sure we have the correct directory
if (isset($input_get_directory)) {
$directory = FCPATH . 'image/catalog/' . $input_get_directory;
} else {
// Do not add extra tralier slash at end /
$directory = FCPATH . 'image/catalog';
}
// Check its a directory
if (!is_dir($directory)) {
$json['error'] = $this->lang->line('error_directory');
}
if (!$json) {
$input_get_folder = $this->input->post('folder');
// Sanitize the folder name
$folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode($input_get_folder, ENT_QUOTES, 'UTF-8')));
// Validate the filename length
if ((utf8_strlen($folder) < 3) || (utf8_strlen($folder) > 128)) {
$json['error'] = $this->lang->line('error_folder');
}
// Check if directory already exists or not
if (is_dir($directory . '/' . $folder)) {
$json['error'] = $this->lang->line('error_exists');
}
}
if (!$json) {
mkdir($directory . '/' . $folder, 0777);
$json['success'] = $this->lang->line('text_directory');
}
$this->output->set_content_type('Content-Type: application/json');
$this->output->set_output(json_encode($json));
}
public function delete()
{
$json = array();
$input_path_post = $this->input->post('path');
if (isset($input_path_post)) {
$paths = $input_path_post;
} else {
$paths = array();
}
// Loop through each path to run validations
foreach ($paths as $path) {
$path = rtrim(FCPATH . 'image/' . str_replace(array('../', '..\\', '..'), '', $path), '/');
// Check path exsists
if ($path == FCPATH . 'image/' . 'catalog') {
$json['error'] = $this->lang->line('error_delete');
break;
}
}
if (!$json) {
// Loop through each path
foreach ($paths as $path) {
$path = rtrim(FCPATH . 'image/' . str_replace(array('../', '..\\', '..'), '', $path), '/');
// If path is just a file delete it
if (is_file($path)) {
unlink($path);
// If path is a directory beging deleting each file and sub folder
} elseif (is_dir($path)) {
$files = array();
// Make path into an array
$path = array($path . '*');
// While the path array is still populated keep looping through
while (count($path) != 0) {
$next = array_shift($path);
foreach (glob($next) as $file) {
// If directory add to path array
if (is_dir($file)) {
$path[] = $file . '/*';
}
// Add the file to the files to be deleted array
$files[] = $file;
}
}
// Reverse sort the file array
rsort($files);
foreach ($files as $file) {
// If file just delete
if (is_file($file)) {
unlink($file);
// If directory use the remove directory function
} elseif (is_dir($file)) {
rmdir($file);
}
}
}
}
$json['success'] = $this->lang->line('text_delete');
}
$this->output->set_content_type('Content-Type: application/json');
$this->output->set_output(json_encode($json));
}
}

Related

Dependent dropdown, second dropdown not populated, Codeigniter

I have a dependent drop down that get the category on the first drop down and should get the subcategory on the second drop down but the subcategory drop down isn't populated. I have something like this in my Model:
public function category()
{
$response = array();
$this->search(array(), 'date_created');
$this->db->select('*');
$query = $this->db->get('categories');
$response = $query->result_array();
return $response;
}
public function sub_category($parent_id)
{
$query = $this->db->get_where('sub_categories', array('parent_id' => $parent_id));
return $query->result_array();
}
And then something like this on my Controller:
public function edit_product($id)
{
$data['title'] = 'Update Product';
$this->load->view('../admin/template/admin_header');
$products = new Admin_model;
$data['products'] = $products->edit_product($id);
$data['category'] = $this->Admin_model->category();
$data['subcategory'] = $this->Admin_model->sub_category($data['products']->category_id);
$this->load->view('../admin/template/admin_topnav');
$this->load->view('../admin/template/admin_sidebar');
$this->load->view('../admin/products/manage_product', $data);
$this->load->view('../admin/template/admin_footer');
}
function get_subcategory()
{
if ($this->input->post('parent_id')) {
echo $this->Admin_model->get_subcategory($this->input->post('parent_id'));
}
}
public function insert_product()
{
$productData = array();
if ($this->input->post('productData')) {
$this->form_validation->set_rules('category_id', 'Category', 'required');
$this->form_validation->set_rules('sub_category_id', 'Sub Category', 'required');
$this->form_validation->set_rules('product_name', 'Product Name', 'required');
$this->form_validation->set_rules('department', 'Department', 'required');
$this->form_validation->set_rules('description', 'Description', 'trim|required');
$this->form_validation->set_rules('status', 'Status', 'required');
if ($this->form_validation->run() == true) {
$ori_filename = $_FILES['product_image']['name'];
$update_image = time() . "" . str_replace(' ', '-', $ori_filename);
$config = [
'upload_path' => './images/products',
'allowed_types' => 'gif|jpg|png',
'file_name' => $update_image,
];
$this->load->library('upload', $config);
if (!$this->upload->do_upload('product_image')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view(base_url('admin/products'), $error);
} else {
$image = $this->upload->data('file_name');
$productData = array(
'category_id' => $this->input->post('category_id'),
'sub_category_id' => $this->input->post('sub_category_id'),
'product_name' => $this->input->post('product_name'),
'department' => $this->input->post('department'),
'description' => $this->input->post(htmlentities('description')),
'status' => $this->input->post('status'),
'upload_path' => $image
);
$img = new Admin_model;
$img->insert_product($productData);
$this->session->set_flashdata('status', 'Package InsertedSuccesfully');
redirect(base_url('admin/products'));
}
}
}
$data['title'] = 'Insert Product';
$data['category'] = $this->Admin_model->category();
$data['subcategory'] = $this->Admin_model->get_subcategory();
$this->load->view('../admin/template/admin_header');
$this->load->view('../admin/template/admin_topnav');
$this->load->view('../admin/template/admin_sidebar');
$this->load->view('../admin/products/manage_product', $data);
$this->load->view('../admin/template/admin_footer');
}
And then the view:
<div class="form-group">
<label for="" class="control-label"> Category</label>
<select name="category_id" id="category" class="custom-select select">
<option value="">Select Category</option>
<?php
foreach ($category as $row) {
echo '<option value="' . $row['id'] . '"';
if (isset($products) && $row['id'] == $products->category_id) {
echo ' selected';
}
echo '>' . $row['category'] . '</option>';
}
?>
</select>
</div>
<div class="form-group">
<label for="" class="control-label">Sub Category</label>
<select name="sub_category_id" id="subcategory" class="custom-select select">
<option value="">Select Sub Category</option>
<?php
foreach ($subcategory as $row) {
echo '<option value="' . $row['id'] . '"';
if ($row['id'] == $products->sub_category_id) {
echo ' selected';
}
echo '>' . $row['sub_category'] . '</option>';
}
?>
</select>
</div>
And here's the script. I'm not really familiar at AJAX so i tried to ask and get answers here which helps me progress but I still can't populate the subcategory drop down.
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function() {
var parent_id = $('#category').val();
console.log(parent_id)
if (parent_id != '') {
$.ajax({
url: "<?php echo base_url(); ?>admin/get_subcategory",
method: "POST",
data: {
parent_id: parent_id
},
success: function(data) {
$('#subcategory').html(data);
console.log(data)
}
});
} else {
$('#subcategory').html('<option value="">Select Category First</option>');
}
});
});
Also, here's what I get in the console
The result from $this->Admin_model->sub_category(...) is an array.
echo works on string values only, which is why you're getting the error. You'll need to loop over the result array (in admin/get_subcategory) and print the values one by one. Also surround each value with an <option> tag so the result can be placed in the select box without further modification:
public function get_subcategory() {
if ($this->input->post('parent_id')) {
$subcategories = $this->Admin_model->sub_category($this->input->post('parent_id'));
foreach ($subcategories as $subcategory) {
echo '<option value="'.$subcategory['id'].'">'.$subcategory['sub_category'].'</option>';
}
}
}

upload multiple pictures in codeigniter

HTML Code
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="file1" size="20" />
<input type="file" name="file2" size="20" />
<input type="submit" value="upload" />
</form>
Controller code
public function do_upload()
{
$pic1 = "Name One";
$pic2 = "Name Two";
$RealName = array('file1', 'file2' );
$ChangeName = array($pic1, $pic2 );
$arrlength = count($ChangeName);
for($x = 0; $x < $arrlength; $x++)
{
$config['upload_path'] = './uploads/';
$config['file_name'] = $ChangeName[$x];
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 1909900;
$this->load->library('upload', $config);
$this->upload->do_upload($RealName[$x]);
echo $ChangeName[$x]; echo "<br>";
echo $RealName[$x]; echo "<br>";
}
}
Trying to upload multiple pictures. Code runs correctly but I'm facing some problems in saving all pictures. The problem is saving all pictures with same name (Name One).
try this one out. this code is I am using...
private function upload_files($path, $title, $files)
{
$config = array(
'upload_path' => $path,
'allowed_types' => 'jpg|gif|png',
'overwrite' => 1,
);
$this->load->library('upload', $config);
$images = array();
foreach ($files['name'] as $key => $image) {
$_FILES['images[]']['name']= $files['name'][$key];
$_FILES['images[]']['type']= $files['type'][$key];
$_FILES['images[]']['tmp_name']= $files['tmp_name'][$key];
$_FILES['images[]']['error']= $files['error'][$key];
$_FILES['images[]']['size']= $files['size'][$key];
$fileName = $title .'_'. $image;
$images[] = $fileName;
$config['file_name'] = $fileName;
$this->upload->initialize($config);
if ($this->upload->do_upload('images[]')) {
$this->upload->data();
} else {
return false;
}
}
return $images;
}

Upload image without form action using dropzone in codeigniter

Upload image without form action using dropzone in CodeIgniter. I need to upload an image without the form action in dropzone. that means, there are one form, dropzone image and other fields are in the form. First when we selecting an image, automatically upload the image and save in the database. And add other fields then submit the form action.
you can Upload image using AJAX with button but a button must be under the form tag with id
View
<form action="<?php echo SURL; ?>admin/registered_students/" id="file_completion_form" class="form-horizontal" method="post" enctype="multipart/form-data">
<td>
<input type="file" data-validation="" style="display: inline" name="undertaking" id="undertaking" value="" placeholder="" multiple="">
</td>
<td>
<input type="hidden" id="student_id" name="student_id" value="<?=$student_id;?>">
<button type="button" class="btn btn-info chk2" id="upload_undertaking">
<i class="fa fa-upload"></i>
</button>
</td>
<td>
<span class="alert" style="display: none" id="msg">Updated</span>
</td>
<td id="download_undertaking">
<a href="<?php echo SURL.'file/download/'.$files[0]['undertaking'];?>">
<button type="button" class="btn btn-info chk2" id=""><i class="fa fa-download"></i></button>
</a>
</td>
</form>
JS
$('#upload_undertaking').click(function(e)
{
e.preventDefault();
var data = new FormData();
var form_data = $('#file_completion_form').serializeArray();
$.each(form_data, function (key, input)
{
data.append(input.name, input.value);
});
//input quatation
var quotation_wip = $('input[name="undertaking"]')[0].files;
if(quotation_wip.length>0)
{
for (var i = 0; i < quotation_wip.length; i++)
{
data.append("undertaking[]", quotation_wip[i]);
}
}
else
{
return 0;
exit;
}
data.append('key', 'value');
var student_id = $('#student_id').val();
$.ajax(
{
url:URL+'file_completion/'+student_id,
type:'POST',
data:data,
cache:false,
contentType: false,
processData: false,
success:function(data)
{
if(data==2)
{
window.location.href=URL+'index/'+student_id;
}
else
{
var obj = jQuery.parseJSON(data);
// alert( obj.undertaking );
$("#undertaking span").html(obj.undertaking);
$("#download_undertaking").html('<button type="button" class="btn btn-info chk2" id=""><i class="fa fa-upload"></i></button>');
$("#msg").show();
setTimeout(function()
{
$("#msg").hide();
},
10000);
}
}
});
});
Controller
public function file_completion1($student_id='',$document_name='')
{
// if($this->input->post('student_id'))
// {
// echo $this->input->post($student_id);
// echo($student_id).'-';
// echo($document_name);
// exit();
$filename=array();
if(count($_FILES['copy_of_paid_fee_challan']['name']) > 0 && $_FILES['copy_of_paid_fee_challan']['name'] !='')
{
$files = $_FILES['copy_of_paid_fee_challan'];
$count = count($_FILES['copy_of_paid_fee_challan']['name']);
//echo $_FILES['file']['name'];exit();
for($i=0; $i<$count;$i++)
{
$config = array();
$projects_folder_path = './assets/uploads/';
$thumb = $projects_folder_path . 'thumb';
$_FILES['copy_of_paid_fee_challan']['name'] = $files['name'][$i];
$_FILES['copy_of_paid_fee_challan']['type'] = $files['type'][$i];
$_FILES['copy_of_paid_fee_challan']['tmp_name'] = $files['tmp_name'][$i];
$_FILES['copy_of_paid_fee_challan']['error'] = $files['error'][$i];
$_FILES['copy_of_paid_fee_challan']['size'] = $files['size'][$i];
// $file_ext = ltrim(strtolower(strrchr($_FILES['copy_of_paid_fee_challan']['name'],'.')),'.');
// $file_name = 'oppein-'.date('YmdGis').'.'.$file_ext;
$config['upload_path'] = $projects_folder_path;
$config['allowed_types'] = '*';
$config['encrypt_name'] = TRUE;
$config['overwrite'] = TRUE;
$config['file_name'] = $_FILES['copy_of_paid_fee_challan']['name'];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload('copy_of_paid_fee_challan'))
{
$error_file_arr = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('err_message', $error_file_arr['error']);
$r=2;
echo json_encode($r);
exit();
}
else
{
$data['delete_record'] = $this->Common_model->select_single_records('uploads',$where=array('student_id'=>$student_id));
if(file_exists($projects_folder_path.$data['delete_record']['undertaking']))
{
unlink($projects_folder_path.$data['delete_record']['undertaking']);
}
$data_image_upload = array('upload_image_data' => $this->upload->data());
$image_name =$data_image_upload['upload_image_data']['file_name'];
$full_path = $data_image_upload['upload_image_data']['full_path'];
// ------------------------------------------------------------------------
$this->load->library('image_lib');
$config['image_library'] = 'GD2';
$config['source_image'] = './assets/uploads/' . $image_name;
$config['maintain_ratio'] = TRUE;
$config['master_dim'] = 'auto';
$config['quality'] = 70;
$config['width'] = 1024;
$config['height'] = 768;
$config['new_image'] = './assets/uploads/' . $image_name;
$this->image_lib->initialize($config);
$this->image_lib->resize();
// ------------------------------------------------------------------------
}
$filename[] = $image_name;
} // end for loop
}
foreach ($filename as $key => $value)
{
$insert_image=array(
'copy_of_paid_fee_challan'=> $value,
// 'student_id' => $student_id,
// 'stage_id' => $stage_id,
'update_date' => date("Y-m-d g:i:s"),
// 'category_status' => 1,
// 'user_id' =>$this->session->userdata('user_id'),
);
// echo "<pre>";
// print_r ($insert_image);
// echo "</pre>";
// exit();
$add_image = $this->Common_model->update_table('uploads',$where=array('student_id'=>$student_id),$insert_image);
}
if ($add_image)
{
$record = $this->Common_model->select_single_records('uploads',$where=array('student_id'=>$student_id));
echo json_encode($record);
}
// }
// else
// {
// $data['active']='registered_students';
// $this->load->view('admin/header',$data);
// $data['student_id']=$student_id;
// $data['error']='';
// $this->load->view('registration/file_completion',$data);
// $this->load->view('admin/footer',$data);
// }
}

Add "active" class to topmenu, magento 1.9

I need to add active class to my topmenu. And i already saw a bunch of subjects on forums, but i didn't saw code like i have. Can you please hepl me. I tried to "echo $currentUrl" but this what i saw " localhost.com/app/etc/local.xml "
<?php $_menu = $this->getHtml('level-top') ?>
<?php if($_menu): ?>
<?php
$currentUrl = Mage::helper('core/url')->getCurrentUrl();
$baseUrl = Mage::getBaseUrl();
$locale = Mage::app()->getLocale()->getLocaleCode();
$_topMenuItems['ru_RU'] = array(
/*$this->__('Home') => $baseUrl,*/
$this->__('IIW, Delivery and payment') => $baseUrl . 'dostavka-oplata.html',
$this->__('IIW, About us') => $baseUrl . 'pro-nas-kategorija.html',
$this->__('IIW, Partners') => $baseUrl . 'partneram.html',
$this->__('IIW, Contacts') => $baseUrl . 'contacts',
$this->__('IIW, It is interesting') => $baseUrl . 'korisna-informacija.html',
/* $this->__('IIW, Where to buy') => $baseUrl . 'de-prudbatu.html', */
);
?>
<nav id="nav">
<ol class="nav-primary">
<?php
$i = 0;
$length = count($_topMenuItems[$locale]);
foreach ($_topMenuItems[$locale] as $label => $_itemUrl) {
if ($i == 0) {
echo $_menu;
}
$customMenuClass = ' cm-' . ($i + 1);
if ($i == 0) {
$customMenuClass .= ' first';
} elseif ($i == ($length - 1)) {
$customMenuClass .= ' last';
}
if (trim($currentUrl, '/') == trim($_itemUrl, '/')) {
$customMenuClass .= ' active';
}
?>
<li class="level0<?php echo $customMenuClass ?>">
<?php echo $label ?>
</li>
<?php
$i++;
}
?>
</ol>
</nav>
<script>
jQuery(document).ready(function($){
var locationUrl = location.href;
$(".yourmenu a.yourclass").each(function() {
var menuLinkHref = $(this).attr("href");
if (~locationUrl.indexOf(menuLinkHref)) {
$(this).addClass("active");
}
});
});
</script>
JS solution if you need
.yourmenu - class of the menu, where your links must change class .actve;
.yourclass - class allready used for each link in the menu (ex.".menu_item_link").

Content not showing in there correct module positions

I have a controller that shows modules for my each position
Array
(
[0] => Array
(
[layout_module_id] => 1
[layout_id] => 1
[module_id] => 1
[position] => column_left
[sort_order] => 1
)
[1] => Array
(
[layout_module_id] => 2
[layout_id] => 1
[module_id] => 2
[position] => column_left
[sort_order] => 2
)
)
Above currently I have only two modules set and the are in the position of column left.
Because the position views are out side of the foreach loop they are picking up that module even though not set for that position? As shown in image.
Question: How can I make sure that the module will only display in its set position view.
public function index() {
$layout_id = $this->getlayoutID($this->router->class);
$modules = $this->getlayoutsmodule($layout_id);
echo '<pre>';
print_r($modules);
echo "</pre>";
$data['modules'] = array();
foreach ($modules as $module) {
$this->load->library('module/question_help');
$data['modules'][] = $this->load->view('module/question_help', $this->question_help->set(), TRUE);
}
// Position Views
$data['column_left'] = $this->load->view('column_left', $data, TRUE);
$data['column_right'] = $this->load->view('column_right', $data, TRUE);
$data['content_top'] = $this->load->view('content_top', $data, TRUE);
$data['content_bottom'] = $this->load->view('content_bottom', $data, TRUE);
// Main view
$this->load->view('welcome_message', $data);
}
public function getlayoutsmodule($layout_id) {
$this->db->select('*');
$this->db->from('layouts_module');
$this->db->where('layout_id', $layout_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result_array();
}
}
Each of the position views have the same foreach loop
<?php if ($modules) { ?>
<?php foreach ($modules as $module) { ?>
<?php echo $module;?>
<?php } ?>
<?php }?>
main view
<div class="container">
<div class="row">
<?php echo $column_left; ?>
<?php if ($column_left && $column_right) { ?>
<?php $class = 'col-sm-6'; ?>
<?php } elseif ($column_left || $column_right) { ?>
<?php $class = 'col-sm-9'; ?>
<?php } else { ?>
<?php $class = 'col-sm-12'; ?>
<?php } ?>
<div id="content" class="<?php echo $class; ?>">
<?php echo $content_top; ?>
<h1>Welcome to CodeIgniter!</h1>
<div id="body">
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you'll find it located at:</p>
<code>application/views/welcome_message.php</code>
<p>The corresponding controller for this page is found at:</p>
<code>application/controllers/Welcome.php</code>
<p>If you are exploring CodeIgniter for the very first time, you should start by reading the User Guide.</p>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds. <?php echo (ENVIRONMENT === 'development') ? 'CodeIgniter Version <strong>' . CI_VERSION . '</strong>' : '' ?></p>
<?php echo $content_bottom; ?>
</div>
<?php echo $column_right; ?></div>
</div>
Got it working I have had to use a foreach switch statement
<?php
class Welcome extends CI_Controller {
public function index() {
$layout_id = $this->getlayoutID($this->router->class);
$column_left = '';
$column_right = '';
$content_top = '';
$content_bottom = '';
$position = array('column_left', 'column_right', 'content_top', 'content_bottom');
foreach ($position as $key) {
switch ($key) {
case 'column_left':
$data['modules'] = array();
$layout_module_results = $this->getlayoutsmodule($layout_id, 'column_left');
if (!empty($layout_module_results)) {
foreach ($layout_module_results as $layout_module_result) {
$data['modules'][] = array(
'position' => $layout_module_result['position']
);
}
}
$column_left = $this->load->view('column_left', $data, TRUE);
break;
case 'column_right':
$data['modules'] = array();
$layout_module_results = $this->getlayoutsmodule($layout_id, 'column_right');
if (!empty($layout_module_results)) {
foreach ($layout_module_results as $layout_module_result) {
$data['modules'][] = array(
'position' => $layout_module_result['position']
);
}
}
$column_right = $this->load->view('column_right', $data, TRUE);
break;
case 'content_top':
$data['modules'] = array();
$layout_module_results = $this->getlayoutsmodule($layout_id, 'content_top');
if (!empty($layout_module_results)) {
foreach ($layout_module_results as $layout_module_result) {
$data['modules'][] = array(
'position' => $layout_module_result['position']
);
}
}
$content_top = $this->load->view('content_top', $data, TRUE);
break;
case 'content_bottom':
$data['modules'] = array();
$layout_module_results = $this->getlayoutsmodule($layout_id, 'content_bottom');
if (!empty($layout_module_results)) {
foreach ($layout_module_results as $layout_module_result) {
$data['modules'][] = array(
'position' => $layout_module_result['position']
);
}
}
$content_bottom = $this->load->view('content_bottom', $data, TRUE);
break;
}
}
$data['column_left'] = $column_left;
$data['column_right'] = $column_right;
$data['content_top'] = $content_top;
$data['content_bottom'] = $content_bottom;
$this->load->view('welcome_message', $data);
}
}

Resources