Today My teacher in my college give me a task about CodeIgniter, he gives me this Controller
public function __construct()
{
parent::__construct();
$this->load->model('Gallery_model');
$this->load->helper(['url','html','form']);
$this->load->database();
$this->load->library(['form_validation','session','image_lib']);
}
public function index()
{
$data = ['images' => $this->Gallery_model->all()];
$this->load->view($this->layoutgaleri, $data);
}
public function add(){
$rules = [
[
'field' => 'caption',
'label' => 'Caption',
'rules' => 'required'
],
[
'field' => 'description',
'label' => 'Description',
'rules' => 'required'
]
];
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/layoutgaleriadd');
}
else
{
/* Start Uploading File */
$config = [
'upload_path' => './asset/images/',
'allowed_types' => 'gif|jpg|png',
'max_size' => 2000,
'max_width' => 640,
'max_height' => 480
];
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/layoutgaleriadd', $error);
}
else
{
$file = $this->upload->data();
//print_r($file);
$data = [
'file' => 'asset/images/' . $file['file_name'],
'caption' => set_value('caption'),
'description' => set_value('description')
];
$this->Gallery_model->create($data);
$this->session->set_flashdata('message','Gambar sudah ditambahkan..');
redirect('admin/Galeri');
}
}
}
public function edit($id){
$rules = [
[
'field' => 'caption',
'label' => 'Caption',
'rules' => 'required'
],
[
'field' => 'description',
'label' => 'Description',
'rules' => 'required'
]
];
$this->form_validation->set_rules($rules);
$image = $this->Gallery_model->find($id)->row();
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/layoutgaleriedit',['image'=>$image]);
}
else
{
if(isset($_FILES["userfile"]["name"]))
{
/* Start Uploading File */
$config = [
'upload_path' => './asset/images/',
'allowed_types' => 'gif|jpg|png',
'max_size' => 2000,
'max_width' => 640,
'max_height' => 480
];
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/layoutgaleriedit',['image'=>$image,'error'=>$error]);
}
else
{
$file = $this->upload->data();
$data['file'] = 'asset/images/' . $file['file_name'];
unlink($image->file);
}
}
$data['caption'] = set_value('caption');
$data['description'] = set_value('description');
$this->Gallery_model->update($id, $data);
$this->session->set_flashdata('message','Gambar sudah diperbarui..');
redirect('admin/galeri');
}
}
public function delete($id)
{
$this->Gallery_model->delete($id);
$this->session->set_flashdata('message','Gambar sudah dihapus..');
redirect('admin/galeri');
}
The problem is we had to create a model that handle function delete, so it can delete a photo from the folder too, here it's the model
public function delete($id)
{
try {
$this->db->where('id',$id)->delete('tb_gambar');
return true;
}
//catch exception
catch(Exception $e) {
echo $e->getMessage();
}
}
He gives us a hint to use unlink, but I don't have any idea how to use it, so I try to ask you all for the answer. I hope you all can show me the right answer for my school task
You can delete image from DB and folder in the one function:
public function delete($id)
{
$image = $this->Gallery_model->find($id)->row();
// delete image
if (is_file('image_path/'.$image->file)) {
unlink('image_path/'.$image->file);
}
$this->Gallery_model->delete($id);
$this->session->set_flashdata('message','Gambar sudah dihapus..');
redirect('admin/galeri');
}
in controller :
public function delete($id)
{
$image = $this->Gallery_model->find($id)->row();
$this->Gallery_model->delete($id);
// use
delete_files(FCPATH.$image->file); // codeigniter method to delete file
// or use php method
// unlink(FCPATH.$image->file); // php unlink method
$this->session->set_flashdata('message','Gambar sudah dihapus..');
redirect('admin/galeri');
}
if(file_exists(FCPATH.$image->file))
{
unlink(FCPATH.$image->file);
}
here is my delete function and it works
public function delete($id){
$image = $this->M_sizechart->find($id)->row();
$this->M_sizechart->delete($id);
if(file_exists(FCPATH.$image->file)) {
unlink(FCPATH.$image->file);
}
$this->session->set_flashdata('message','Image has been deleted..');
redirect(base_url("sizechart"));
}
Related
Attempting to generate thumbnails with Image_moo & CodeIgniter framework. Image_moo does not output any errors, however, thumbnail images are never generated.
dir structure
app
- controllers/
Admin.php
...
- libraries/
Image_moo.php
...
- models/
Admin_photos_model.php
Admin.php
public function photo_upload() {
$rules = [
[
'field' => 'caption',
'label' => 'Caption'//,
//'rules' => 'required'
],[
'field' => 'description',
'label' => 'Description'//,
//'rules' => 'required'
],[
'field' => 'series',
'label' => 'Series',
'rules' => 'required'
]
];
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == FALSE) {
$this->load->view('admin/photos/upload');
} else {
$series = str_replace(' ', '', strtolower($_POST['series']));
$upload_path = './img/photos/'.$series.'/';
$config = [
'upload_path' => $upload_path, //'./img/photos/'.$series.'/',
'allowed_types' => 'gif|jpg|jpeg|png'
];
$this->load->library('upload', $config);
if (!file_exists($upload_path)) { //check if series dir exists
mkdir($upload_path, 0777, true); // create dir if !exist
$num = 1; //init
} else {
$num = $this->db->where('series', $series)->count_all_results('photos') + 1;
};
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/photos/upload', $error);
} else {
$file = $this->upload->data();
$caption = $_POST['caption'];
$description = $_POST['description'];
$data = [
'filename' => $file['file_name'],
'series' => $series,
'num' => $num,
'caption' => $caption,
'description' => $description
];
$this->Admin_photos_model->upload($data);
$this->load->library('image_moo'); //create thumbnail, upload
$file_raw_name = $this->upload->data('raw_name');
$file_ext = $this->upload->data('file_ext');
$file_width = $this->upload->data('image_width');
$file_height = $this->upload->data('image_height');
$file_uploaded = $upload_path.$data['filename']; //$field_info->upload_path.'/'.$uploader_response[0]->name;
if ($file_width > 1024 && $file_height > 720) {
$this->image_moo->load($file_uploaded)
->resize_crop(1024,720)->save($upload_path.$file_raw_name.'_thumb_xl'.$file_ext)
->resize_crop(800,562)->save($upload_path.$file_raw_name.'_thumb_lg'.$file_ext)
->resize_crop(640,450)->save($upload_path.$file_raw_name.'_thumb_med'.$file_ext)
->resize_crop(450,316)->save($upload_path.$file_raw_name.'_thumb_sm'.$file_ext)
->resize_crop(222,156)->save($upload_path.$file_raw_name.'_thumb_xs'.$file_ext);
$data = [
'has_thumb_xl' => 1,
'has_thumb_lg' => 1,
'has_thumb_med' => 1,
'has_thumb_sm' => 1,
'has_thumb_xs' => 1,
'thumb_xl_filename' => $file_raw_name.'_thumb_xl'.$file_ext,
'thumb_lg_filename' => $file_raw_name.'_thumb_lg'.$file_ext,
'thumb_med_filename' => $file_raw_name.'_thumb_med'.$file_ext,
'thumb_sm_filename' => $file_raw_name.'_thumb_sm'.$file_ext,
'thumb_xs_filename' => $file_raw_name.'_thumb_xs'.$file_ext
];
};
if ($this->image_moo->error) {
print $this->image_moo->display_errors();
};
$this->Admin_photos_model->thumbnails($data);
$this->session->set_flashdata('message','file uploaded: '.$file_uploaded.'New image has been added..'.'series dir: '.$series.'last num of series: '.$num.'thumb:'.$file_raw_name.'_thumb_xl'.$file_ext.'errors: '.$this->image_moo->display_errors());
redirect('admin/photos');
};
Admin_photos_model
<?php
class Admin_photos_model extends CI_Model {
public function __construct(){
$this->load->database();
}
public function upload($data) {
try {
$this->db->insert('photos', $data);
return true;
} catch (Exception $e) {
echo $e->getMessage();
};
}
public function thumbnails($data) {
try {
$this->db->insert('photos', $data);
return true;
} catch (Exception $e) {
echo $e->getMessage();
};
}
}
Attempting to generate thumbnails, I'm separating the photos by series. If the series hasn't started, a new dir is created. Ideally, uploading 'waterfall.jpg' with series 'nature' would yield:
app
...
public_html/
img/
photos/
nature/
waterfall.jpg
waterfall_thumb_xl.jpg
waterfall_thumb_lg.jpg
waterfall_thumb_med.jpg
waterfall_thumb_sm.jpg
waterfall_thumb_xs.jpg
Any help would be appreciated.
Reading the image_moo documentation, the save function needs to have an overwrite=FALSE/TRUE. Doing so seemed to fix it.
"save($x,$overwrite=FALSE) - Saved the manipulated image (if
applicable) to file $x - JPG, PNG, GIF supported. If overwrite is not
set file write may fail. The file saved will be dependant on
processing done to the image, or a simple copy if nothing has been
done."
Please help! I was using codeigniter 3 mvc and my code worked just fine. Then I moved to hmvc and my uploads no longer function. Below is my code:
class Home extends MY_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('User_m', 'user');
$this->load->library('upload');
}
public function register()
{
$data['services'] = $this->user->get_service_list();
$data['page_class'] = 'register-page';
$data['title'] = 'Registration';
$data['content_view'] = 'Home/register_v';
$this->template->login_template($data);
}
public function apply()
{
$directoryname = $this->input->post('company').'/documents';
if (!is_dir('customer_documents/'.$directoryname))
{
mkdir('./customer_documents/' . $this->input->post('name_of_org').'/documents', 0777, TRUE);
}
//Field Rules
$this->form_validation->set_rules('company', 'Company/', 'trim|required|min_length[6]');
$this->form_validation->set_rules('address', 'Physical Address', 'trim|required');
$this->form_validation->set_rules('tel', 'Tel', 'trim|required');
$this->form_validation->set_rules('postal_address', 'Postal Address', 'trim|required');
$this->form_validation->set_rules('contact_name', 'Contact Name', 'trim|required|min_length[6]');
$this->form_validation->set_rules('contact_number', 'Contact Number', 'trim|required|min_length[6]');
$this->form_validation->set_rules('position', 'Position', 'trim|required|min_length[6]');
$this->form_validation->set_rules( 'email', 'Email', 'trim|required|valid_email|min_length[7]');
$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' => './customer_documents/'.$directoryname,
'allowed_types' => 'gif|jpg|png|pdf',
'max_size' => '1000000',
'overwrite' => FALSE,
'remove_spaces' => TRUE,
'encrypt_name' => FALSE
];
$this->upload->initialize($config);
$this->upload->do_upload();
$file_data = $this->upload->data();
$name_array[] = $file_data['file_name'];
}
if($this->form_validation->run() == FALSE && !$this->upload->do_upload())
{
$data['error'] = $this->upload->display_errors();
$data['services'] = $this->customer->get_service_list();
//Load Template
$data['page_class'] = 'register-page';
$data['title'] = 'Registration';
$data['content_view'] = 'Home/register_v';
$this->template->login_template($data);
}
else
{
$names= implode(',', $name_array);
$data = array(
'name_of_org' => $this->input->post('name_of_org'),
'address' => $this->input->post('address'),
'tel' => $this->input->post('tel'),
'postal_address' => $this->input->post('postal_address'),
'contact_name' => $this->input->post('contact_name'),
'contact_number' => $this->input->post('contact_number'),
'role' => 'admin',
'position' => $this->input->post('position'),
'email' => $this->input->post('email'),
'userfile' => $names,
'service' => $this->input->post('service_id'),
);
//Insert User
$this->user->register($data);
//isset Message
$this->session->set_flashdata('success', 'You have successfully submitted your registration.');
//Redirect
redirect('Home/register');
}
}
Model:
class User_m extends CI_MODEL{
function __construct()
{
parent::__construct();
$this->table = 'users';
}
function register($data)
{
$this->db->insert($this->table, $data);
}
}
When I use the above code to upload files using mvc it works perfectly well but when I transfered it to hmvc it just post other form fields to the database without files yet also creating directory without uploading any files. What might be the problem? Anyone with a solution for this I am stuck. Please help!
Try with absolute path
(!is_dir(FCPATH.'customer_documents/'.$directoryname))
and fix that in all places accordingly.
Also CI_MODEL should be CI_Model
i have a mistake uploading some images on "multiple upload". If i try to upload the galeries without these images the widget works correctly.
The Image: http://s27.postimg.org/a6qosyctv/Esta_Imagen_Tira_Error.jpg
My form:
$form = ActiveForm::begin([
'id' => 'Item',
'layout' => 'horizontal',
'enableClientValidation' => false,
'errorSummaryCssClass' => 'error-summary alert alert-error',
'options' => ['enctype'=>'multipart/form-data']
]);
$form->field($gallery, 'images[]')->widget(\kartik\file\FileInput::classname(), [
'options' => [
'multiple' => true,
],
'pluginOptions' => [
'uploadUrl' => 'javascript:;',
'showCaption' => false,
'showUpload' => false,
'overwriteInitial' => false,
'allowedFileExtensions' => ['jpg', 'jpeg', 'png'],
'layoutTemplates' => [
'actionUpload' => '',
],
'browseIcon' => '',
'browseLabel' => Yii::t('app', 'Select Files'),
'browseClass' => 'btn btn-block',
'removeLabel' => Yii::t('app', 'Remove All File'),
'removeClass' => 'btn btn-block',
],
]);
My controller:
public function actionCreate()
{
$model = new Hotel();
$model->setCurrentLanguage();
$model->itemType = IElement::ITEM_TYPE_HOTEL;
if ($model->load($_POST)) {
$model->coverPhoto = UploadedFile::getInstance($model, 'coverPhoto');
if ($model->save()) {
if (isset($_POST['Gallery'])) {
$gallery = new Gallery();
$gallery->setAttributes($_POST['Gallery']);
$gallery->idElement = $model->idItem;
$gallery->itemType = IElement::ITEM_TYPE_HOTEL;
$gallery->images = UploadedFile::getInstances($gallery, 'images');
$gallery->save();
}
return $this->redirect(['index']);
}
}
return $this->render('create', [
'model' => $model,
'gallery' => new Gallery(),
]);
}
Gallery Model:
public $images = [];
public function rules()
{
return array_merge(parent::rules(), [
[['images', 'removedImages'], 'safe']
]);
}
public function save($runValidation = true, $attributeNames = null)
{
$transaction = $this->getDb()->beginTransaction();
if(parent::save($runValidation, $attributeNames)){
foreach($this->images as $image){
/* #var UploadedFile $image */
if(!GalleryItem::generateFromImage($image, $this)){
$transaction->rollBack();
return false;
}
}
if(strlen($this->removedImages) > 0){
foreach(explode(',', $this->removedImages) as $itemId){
$albumItem = GalleryItem::findOne($itemId);
if($albumItem instanceof GalleryItem && !$albumItem->delete()){
$transaction->rollBack();
return false;
}
}
}
$transaction->commit();
return true;
}
$transaction->rollBack();
return false;
}
Gallery Item Model:
public static function generateFromImage($imageFile, $gallery)
{
$image = new self;
$image->idGallery = $gallery->primaryKey;
$image->galleryItemOrder = time();
$path = $image->getBasePath();
if(!file_exists($path)) {
mkdir($path, 0777, true);
}
$name = uniqid().'_'.strtr($imageFile->name, [' '=>'_']);
$imageFile->saveAs($path.DIRECTORY_SEPARATOR.$name);
$image->picture = $name;
// var_dump($image->attributes);die();
if(!$image->save()){
#unlink($path.DIRECTORY_SEPARATOR.$name);
return false;
}
return true;
}
I have a form which accepts some text input fields and a file field (used to upload image).
My problem is like that, if I did not fill one of the required fields and I have selected a valid image file, I will get an error message about the missing field, but the image will be uploaded. The Controller is:
defined('BASEPATH') OR exit('No direct script access allowed');
class Manage extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$config = array(
array(
'field' => 'item_name',
'label' => 'Item name',
'rules' => 'required'
),
array(
'field' => 'item_code',
'label' => 'Item code',
'rules' => 'required|is_unique[_items.item_code]'
),
array(
'field' => 'item_description',
'label' => 'Item description',
'rules' => 'required'
),
array(
'field' => 'item_img',
'label' => 'Item image',
'rules' => 'callback_upload_image'
)
);
$this->form_validation->set_rules($config);
$this->form_validation->set_message('is_unique', 'Item code (' . $this->input->post('item_code') . ') already exists.');
if($this->form_validation->run() == FALSE)
{
// Render the entry form again
}
else
{
// Go to another page
}
}
public function upload_image()
{
$config['upload_path'] = './items_images';
$config['max_size'] = 1024 * 10;
$config['allowed_types'] = 'gif|png|jpg|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if(isset($_FILES['item_img']) && !empty($_FILES['item_img']['name']))
{
if($this->upload->do_upload('item_img'))
{
$upload_data = $this->upload->data();
$_POST['item_img'] = $upload_data['file_name'];
return TRUE;
}
else
{
$this->form_validation->set_message('upload_image', $this->upload->display_errors());
return FALSE;
}
}
else
{
$_POST['item_img'] = NULL;
return FALSE;
}
}
}
As I know, if one rule failed, other fields and operations will be canceled and the form will be loaded again, or other operations will be done.
Thank you,,,
you need to upload the image when validation is true only. so remove your public function upload_image() and write the functionalists inside validation true statement as given below.
defined('BASEPATH') OR exit('No direct script access allowed');
class Manage extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$config = array(
array(
'field' => 'item_name',
'label' => 'Item name',
'rules' => 'required'
),
array(
'field' => 'item_code',
'label' => 'Item code',
'rules' => 'required|is_unique[_items.item_code]'
),
array(
'field' => 'item_description',
'label' => 'Item description',
'rules' => 'required'
),
array(
'field' => 'item_img',
'label' => 'Item image',
'rules' => 'callback_upload_image'
)
);
$this->form_validation->set_rules($config);
$this->form_validation->set_message('is_unique', 'Item code (' . $this->input->post('item_code') . ') already exists.');
if($this->form_validation->run() == FALSE)
{
// Render the entry form again
}
else
{
$config['upload_path'] = './items_images';
$config['max_size'] = 1024 * 10;
$config['allowed_types'] = 'gif|png|jpg|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if(isset($_FILES['item_img']) && !empty($_FILES['item_img']['name']))
{
if($this->upload->do_upload('item_img'))
{
$upload_data = $this->upload->data();
$_POST['item_img'] = $upload_data['file_name'];
return TRUE;
}
else
{
$this->form_validation->set_message('upload_image', $this->upload->display_errors());
return FALSE;
}
}
else
{
$_POST['item_img'] = NULL;
return FALSE;
}
}
// Go to another page
}
}
I found this very helpful post here. The author wrote his own rules to validate the file chosen by user to upload. Code sample:
$this->form_validation->set_rules('file', '', 'callback_file_check');
public function file_check($str){
$allowed_mime_type_arr = array('application/pdf','image/gif','image/jpeg','image/pjpeg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['file']['name']);
if(isset($_FILES['file']['name']) && $_FILES['file']['name']!=""){
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message('file_check', 'Please select only pdf/gif/jpg/png file.');
return false;
}
}else{
$this->form_validation->set_message('file_check', 'Please choose a file to upload.');
return false;
}
}
i'am not able to do upload image with lines of code in function add()
just provide me with some solution for uploading image
public function add()
{
if ($this->input->server('REQUEST_METHOD') === 'POST')
{
$this->form_validation->set_rules('image', 'image', 'required');
$this->form_validation->set_rules('text', 'text', 'required');
$this->form_validation->set_error_delimiters('<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>', '</strong></div>');
if ($this->form_validation->run())
{
**$data_to_insert = array(
'image' => $this->input->post('image'),
'text' => $this->input->post('text'),**
);
if($this->home_banner_model->insert_home_banner($data_to_insert)){
$data['flash_message'] = TRUE;
}else{
$data['flash_message'] = FALSE;
}
}
}
$data['main_content'] = 'admin/home_banner/add';
$this->load->view('includes_admin/template', $data);
}
$config = array(
'upload_path' => 'uploadPath',
'allowed_types' => 'jpg,jpeg',
'max_size' => 1500
);
$this->load->library('upload', $config);
if(isset($_FILES['field_name']) && $_FILES[field_name]['name'] != NULL)
if($this->upload->do_upload('field_name'))
{
$upload_data = $this->upload->data();
$data_to_insert = array(
'attachment_link' => 'uploadPath/'.$upload_data['file_name'],
'attachment_size' => $upload_data['file_size']
// u can add parameters as for ur table to save
);
$this->home_banner_model->insert_home_banner($data);
}
else
{
echo $this->upload->display_errors();
}