Image_moo & CodeIgniter framework won't generate thumbnails - php

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."

Related

How to delete older image from public folder on upload using Laravel

I have folder in my public folder profile_images where my images are being stored. I want to delete older image from this folder when new image is uploaded.
How I can delete my older file on upload?
Here is my whole controller code:
public function uploadImage(Request $request)
{
$user_id = $request->input('user_id');
$image = $request->input('image');
$r = [
'user_id' => $user_id,
];
$validator = Validator::make($r, [
'user_id' => 'required|exists:users,id',
]);
if($validator->fails()) {
return response(['status' => false, 'message' => 'Validation Errors', 'errors' => $validator->errors()->all()], 500);
}
if ($validator->fails()) {
return response([
'status' => false,
'message' => __('messages.validation_errors'),
'errors' => $validator->errors()->all()], 200);
}
try {
$path = public_path('profile_images');
#mkdir($path, '0777', true);
$image = base64_decode($image);
$imageName = str_random(10).'.'.'png';
Storage::disk('profile-image')->put($imageName, $image);
$path = asset('public/profile_images/' . $imageName);
$this->userBasicInfo->where('user_id', $user_id)->update(['profile_pic' => $path]);
return response(['status' => true, 'message' => 'Image Uploaded successfully', 'data' => ['profile_image' => $path]], 200);
} catch (\Exception $ex) {
return response(['status' => false, 'message' => $ex->getMessage()], 500);
}
}
Laravel have methods to deleting files:
Storage::delete('profile-image/old_file.jpg');
Also, you should to remember old file name to delete it in the future:
$imageName = str_random(10).'.'.'png';
Save this imageName somewhere or use your user_id to know what image you want to delete.
The default method to delete any file in public directory
File::delete(public_path('file path and name'));

How to delete images from folder in Codeigniter

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

fileUploadErrorAttack file was illegally uploaded. This could be a possible attack

I am working on multiple image uploads i got the problem that 1st image is uploading properly and for second image it shows out the file upload error attack
Can you help me to find out the problem
Controller
public function mimageAction()
{
$form = new MultipleImageForm();
$form->get('submit')->setValue('Submit');
$request = $this->getRequest();
if($request->isPost())
{
$nonFile = $request->getPost()->toArray();
$File = $this->params()->fromFiles('file');
$data = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
//print_r($data); die;
$form->setData($data);
if ($form->isValid())
{
$count = count($data['varad']);
// $dataNew=array(
// 'test'=>trim($data['test']),
// 'file'=>trim($data['file']['name']),
// 'image'=>trim($data['image']['name'])
// );
$request = new Request();
$files = $request->getFiles();
for($i=0;$i<$count;$i++)
{
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination('public/img/upload/'); // Returns all known internal file information
//$adapter->addFilter('File\Rename', array('target' =>"public/img/upload" . DIRECTORY_SEPARATOR .$data['varad'][$i]['name'] , 'overwrite' => true));
$filter = new \Zend\Filter\File\RenameUpload("public/img/upload/");
$filter->filter($files['varad'][$i]['name']);
$filter->setUseUploadName(true);
$filter->filter($files['varad'][$i]['name']);
if(!$adapter->receive())
{
$messages = $adapter->getMessages();
print_r($messages);
}
else
{
echo "Image Uploaded";
}
}
// $adapter = new \Zend\File\Transfer\Adapter\Http();
// $adapter->setDestination('public/img/upload/'); // Returns all known internal file information
// $adapter->addFilter('File\Rename', array('target' =>"public/img/upload" . DIRECTORY_SEPARATOR .$image2, 'overwrite' => true));
//
// if(!$adapter->receive())
// {
// $messages = $adapter->getMessages();
// print_r($messages);
// }
// else
// {
// echo "Image Uploaded";
// }
}
}
return array('form' => $form);
}
Form
public function __construct($name = null)
{
parent::__construct('stall');
$this->setAttribute("method","post");
$this->setAttribute("enctype","multipart/form-data");
$this->add(array(
'name' => 'varad',
'attributes' => array(
'type' => 'file',
'multiple'=>'multiple',
),
'options' => array(
'label' => 'First Image',
),
'validators' => array(
'Size' => array('max' => 10*1024*1024),
)
));
$this->add(array(
'name' => 'test',
'attributes' => array(
'type' => 'text',
),
'options' => array(
'label' => 'Text Box',
),
));
$this->add(array(
'name' => 'varad',
'attributes' => array(
'type' => 'file',
'multiple'=>'multiple',
),
'options' => array(
'label' => 'Second Image',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'submit',
));
}
Here i also tried by getting different names for images as well as different procedures for images
I think u can't use
$request->getFiles();
for this solution.
Please try to use $adapter->getFileInfo()
It's getting files from const _FILES.
I give my example for u:
$adapter = new Zend_File_Transfer_Adapter_Http();
$newInfoData = [];
$path = $this->getBannerDirByBannerId($banner->getId());
foreach ($adapter->getFileInfo() as $key => $fileInfo) {
if (!$fileInfo['name']) {
continue;
}
if (!$adapter->isValid($key)) {
return $this->getPartialErrorResult($adapter->getErrors(), $key);
}
$fileExtension = pathinfo($fileInfo['name'], PATHINFO_EXTENSION);
$newFileName = $key . '.' . $fileExtension;
if (!is_dir($path)) {
#mkdir($path, 0755, true);
}
$adapter->addFilter('Rename', array(
'target' => $path . $newFileName,
'overwrite' => true
));
$isReceive = $adapter->receive($key);
if ($isReceive) {
$newInfoData[$key] = $newFileName;
}
}
if (!empty($newInfoData)) {
$newInfoData['id'] = $banner->getId();
return BannerModel::getInstance()->updateBanner($newInfoData);
} else {
return new Model_Result();
}

Magento file upload don't delete or update the file uploaded

Just a continuation of my study about Magento Admin Grid. I'm trying to create a File Upload and I am successfully made it. However, I'm encountering a problem regarding the update and delete of the file upload form field. The other input form fields are populated with data and can be updated and deleted from the records.
Problem:
When tried to update the records, the file upload field was not displaying the name of the uploaded file, and when try to update it, the old uploaded file was not deleted but the file path was updated on the records.
When try to delete the records, the uploaded file was not deleted but deleted on the record.
I also have minor issue regarding the grid. The grid is not displaying the ID of the records and other integer or number even if they were declared on the grid.
Question:
What am I missing in my update form fields and grid?
Here is a sample of my form fields.
$fieldset->addField('title', 'text', array(
'label' => Mage::helper('pmadmin')->__('Matrix Title'),
'class' => 'required-entry',
'required' => true,
'name' => 'title',
));
$fieldset->addField('file_path', 'file', array(
'label' => Mage::helper('pmadmin')->__('File'),
'value' => '',
'class' => 'required-entry',
'required' => true,
'disabled' => false,
'readonly' => true,
'name' => 'file_path',
));
$fieldset->addField('short_description', 'text', array(
'label' => Mage::helper('pmadmin')->__('Short Description'),
'class' => 'required-entry',
'required' => true,
'name' => 'short_description',
));
Here is my controller
public function editAction()
{
$pmadminId = $this->getRequest()->getParam('id');
$pmadminModel = Mage::getModel('pmadmin/pmadmin')->load($pmadminId);
if ($pmadminModel->getId() || $pmadminId == 0) {
Mage::register('pmadmin_data', $pmadminModel);
$this->loadLayout();
$this->_setActiveMenu('pmadmin/items');
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item Manager'), Mage::helper('adminhtml')->__('Item Manager'));
$this->_addBreadcrumb(Mage::helper('adminhtml')->__('Item News'), Mage::helper('adminhtml')->__('Item News'));
$this->getLayout()->getBlock('head')->setCanLoadExtJs(true);
$this->_addContent($this->getLayout()->createBlock('pmadmin/adminhtml_pmadmin_edit'))
->_addLeft($this->getLayout()->createBlock('pmadmin/adminhtml_pmadmin_edit_tabs'));
$this->renderLayout();
} else {
Mage::getSingleton('adminhtml/session')->addError(Mage::helper('pmadmin')->__('Item does not exist'));
$this->_redirect('*/*/');
}
}
public function newAction()
{
$this->_forward('edit');
}
public function saveAction() {
$post_data=$this->getRequest()->getPost();
if ($post_data) {
try {
//save file to the destination folder
if (isset($_FILES)){
if ($_FILES['file_path']['name']) {
$path = Mage::getBaseDir('media') . DS . 'rts' . DS .'pmadmin'.DS;
$uploader = new Varien_File_Uploader('file_path');
$uploader->setAllowedExtensions(array('PDF','pdf'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$destFile = $path.$_FILES['file_path']['name'];
$filename = $uploader->getNewFileName($destFile);
$uploader->save($path, $filename);
$post_data['file_path']='rts/pmadmin/'.$filename;
}
}
//save file path to the database
$model = Mage::getModel("pmadmin/pmadmin")
->addData($post_data)
->setId($this->getRequest()->getParam("id"))
->save();
Mage::getSingleton("adminhtml/session")->addSuccess(Mage::helper("adminhtml")->__("File was successfully saved"));
Mage::getSingleton("adminhtml/session")->setPmadminData(false);
if ($this->getRequest()->getParam("back")) {
$this->_redirect("*/*/edit", array("id" => $model->getId()));
return;
}
$this->_redirect("*/*/");
return;
}
catch (Exception $e) {
Mage::getSingleton("adminhtml/session")->addError($e->getMessage());
Mage::getSingleton("adminhtml/session")->setPmadminData($this->getRequest()->getPost());
$this->_redirect("*/*/edit", array("id" => $this->getRequest()->getParam("id")));
return;
}
}
$this->_redirect("*/*/");
}
public function deleteAction()
{
if( $this->getRequest()->getParam('id') > 0 ) {
try {
$pmadminModel = Mage::getModel('pmadmin/pmadmin');
$pmadminModel->setId($this->getRequest()->getParam('id'))
->delete();
Mage::getSingleton('adminhtml/session')->addSuccess(Mage::helper('adminhtml')->__('Item was successfully deleted'));
$this->_redirect('*/*/');
} catch (Exception $e) {
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
}
}
$this->_redirect('*/*/');
}
Note:
I am able to successfully update other form fields and the file path from the records but not the file uploaded.
you have to add else statment if the user is not uploading for the edit. $postdata['file_path']['value'] this is created by magento automatically.
if (isset($_FILES)){
if ($_FILES['file_path']['name']) {
$path = Mage::getBaseDir('media') . DS . 'rts' . DS .'pmadmin'.DS;
$uploader = new Varien_File_Uploader('file_path');
$uploader->setAllowedExtensions(array('PDF','pdf'));
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$destFile = $path.$_FILES['file_path']['name'];
$filename = $uploader->getNewFileName($destFile);
$uploader->save($path, $filename);
$post_data['file_path']='rts/pmadmin/'.$filename;
}
else {
$postdata['file_path']=$postdata['file_path']['value'];
}
}

CMultiFileUpload class not inserting image names on the database yii

I'm working on multi file(images) uploading functionality.
I've tried everything I got.
It's not working.
It's uploading images on the path I specified but not inserting image's names on the table column.
The table's column name is "sample"
Here's the snippet of the view:
$this->widget('CMultiFileUpload', array(
'model' => $model,
'name' => 'sample',
'attribute' => 'sample',
'accept' => 'jpeg|jpg|gif|png',
'duplicate' => 'Duplicate file!',
'denied' => 'Invalid file type',
'remove' => '[x]',
'max' => 20,
));
This is the controller's code the(the function that dealing with the part):
public function actionCreate($project_id) {
$model = new Bid();
$project = $this->loadModel('Project', $project_id);
if (count($project->bids) == 5) {
Yii::app()->user->setFlash('warning', Yii::t('bids', 'This project has already reached its maximum number of bids, so you cannot post a new bid.'));
$this->redirect(array('project/view', 'id' => $project_id));
}
if (!empty($project->bid)) {
Yii::app()->user->setFlash('warning', Yii::t('bids', 'This project has a selected bid already, so you cannot post a new bid.'));
$this->redirect(array('project/view', 'id' => $project_id));
}
if ($project->closed) {
Yii::app()->user->setFlash('warning', Yii::t('bids', 'You cannot add bids as this project has been closed.'));
$this->redirect(array('project/view', 'id' => $project_id));
}
$model->project = $project;
if (isset($_POST['Bid'])) {
$model->attributes = $_POST['Bid'];
$photos = CUploadedFile::getInstancesByName('sample');
if (isset($photos) && count($photos) > 0) {
foreach ($photos as $image => $pic) {
$pic->name;
if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/'.$pic->name)) {
// add it to the main model now
$img_add = new Bid();
$img_add->filename = $pic->name;
$img_add->save();
}
else {
}
}
}
$model->project_id = $project->id;
$model->freelancer_id = $this->currentUser->id;
if ($model->save()) {
$this->redirect(array('project/view', 'id' => $project->id, '#' => 'bidslist'));
}
}
$this->render('create', array(
'model' => $model,
));
}
Thanks in Advance.
Please let me know if anyone needs anything else for better understanding.
If i underssot you correctly when you saving the model
$img_add = new Bid();
$img_add->sample = $pic->name;
$img_add->save();

Categories