Codeigniter 3 upload not saving thumb to directory - php

I am trying to save the thumbnail image to the directory, but it is not working. I am able to save the original image and save info to database, but for some reason the thumbnail is not saving to the thumbs directory I create. The directory has read/write access. I will also note I am using Dropzone.js.
Here is my partial code:
if ( ! $this->upload->do_upload('file'))
{
//upload failed, echo back negative response to dropzone.js
}
else
{
//upload success, upload file(s)
$image_data = $this->upload->data();
$img_config['source_image'] = '/uploads/videos/'.$image_data['file_name'];
$img_config['new_image'] = '/uploads/videos/thumbs/'.$image_data['file_name'];
$img_config['create_thumb'] = TRUE;
$img_config['maintain_ratio'] = TRUE;
$img_config['width'] = 251;
$img_config['height'] = 180;
$this->load->library('image_lib', $img_config);
$this->image_lib->resize();
$file = array(
'user_id' => $this->my_auth->logged_in(),
'img_name' => $image_data['raw_name'],
'thumb_name' => $image_data['raw_name'].'_thumb',
'ext' => $image_data['file_ext'],
'upload_date' => time()
);
$this->upload_model->add_image($file);
$data['img_success'] = '<div class="alert alert-success" id="imgSuccess">Your image <strong>' . $image_data['file_name'] . '</strong> was successfully uploaded!</div>';
$this->load->view('templates/frontend/front_header', $data);
$this->load->view('templates/frontend/front_navbar');
$this->load->view('frontend/upload_images', $data);
$this->load->view('templates/frontend/front_footer', $data);
}
I am able to successfully save the original image, just not the thumbnail. Can anyone see anything wrong here?

I added this to my __construct:
$this->original_path = realpath(APPPATH.'../uploads/images');
$this->thumbs_path = realpath(APPPATH.'../uploads/images/thumbs');
and changed the source_image and new_image configs:
$img_config['source_image'] = $image_data['full_path'];
$img_config['new_image'] = $this->thumbs_path;
This seems to have fixed it.

Related

adding timestamp while uploading image file is not working

I am developing a ad site that anyone able to upload 3 images.
So I am coding to upload that 3 images by adding timestamp in front of their file name to make them unique. I use codeigniter framework and attaching the code below.
when I submitting form data, localhost server shows that images have been saved correctly with some code infornt of image filename. But problem is there are no images saved in relevant image folder in that name and I cannot retrieve that images in next preview advertisement page.
I don't know much about php or codeignitor. Your help is highly appreciated.
$config['upload_path'] = './assets/images/adsimages';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5120;
$this->load->library('upload',$config);
$this->upload->initialize($config);
if (!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'no_image.jpg';
}
else {
$data = array('upload_data' => $this->upload->data());
$post_image1 = time().$_FILES['userfile1']['name'];
$post_image2 = time().$_FILES['userfile2']['name'];
$post_image3 = time().$_FILES['userfile3']['name'];
}
$result = $this->post_model->adregister($post_image1,$post_image2,$post_image3);
You can append time to 'filename' in config of upload library
$config['file_name'] = time().$_FILES['userfile1']['name'];
Or if you want unique name for all files the simply add
$config['encrypt_name'] = TRUE;
then
$this->load->library('upload', $config);
Try this one:-
$path = pathinfo($_FILES["userfile1"]["name"]);
$image_path = $path['filename'].'_'.time().'.'.$path['extension'];
I've written a possible solution for your code. You haven't shared your full code so you'll have to fill in the gaps yourself and maybe make some changes here and there; Comments are mentioned wherever necessary. See if it helps you.
public function your_function_name(){
// your-code
// your-code
// check if file is uploaded in field1
if(!empty($_FILES['userfile1']['name'])){
// call function to upload file
$userfile1 = $this->upload_file('userfile1');
}
// check if file is uploaded in field2
if(!empty($_FILES['userfile2']['name'])){
$userfile2 = $this->upload_file('userfile2');
}
// check if file is uploaded in field3
if(!empty($_FILES['userfile3']['name'])){
$userfile3 = $this->upload_file('userfile3');
}
$result = $this->post_model->adregister($userfile1, $userfile2, $userfile3);
}
// function to upload file
function upload_file($filename){
$config['file_name'] = time().$_FILES[$filename]['name']; // append time to filename
$config['upload_path'] = './assets/images/adsimages';
$config['allowed_types'] = 'gif|jpg|jpeg|png|GIF|JPG|PNG|JPEG';
$config['max_size'] = 5120;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$uploaded = $this->upload->do_upload($filename);
if ( ! $uploaded ){
$error = array('error' => $this->upload->display_errors());
$file = 'no_image.jpg'; // default file
}else{
$upload_data = $this->upload->data();
$file = $upload_data['file_name']; // uploaded file name
}
return $file; // return filename
}

Codeigniter 3 image upload bug: image filename is incremented, but not updated in the posts table

I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.
Every post has a main image hence, there is a post_image column in the posts table.
I have this problem when a post's image is replaced with a new image, that has the same (file)name as the old one: the image filename is incremented - mypic.jpg becomes mypic1.jpg - but the filename string is not updated in the posts table.
The code is this and I believe I have identified the source of the problem (commented):
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
//Keep the current image name in the posts table
//If no new image is loaded
$post_image = $this->input->post('postimage');
} else {
$data = array('upload_data' => $this->upload->data());
// This line is the source of the problem
$post_image = $_FILES['userfile']['name'];
}
I don't know how to increment it properly or even if increment is the best solution.
The question: What is the most robust (reliable) way to solve this problem?
EDIT:
For consistency, I should probably update the initial (when the post is created) upload code:
if (!$this -> upload -> do_upload()) {
$errors = array('error' => $this -> upload -> display_errors());
$post_image = 'default.jpg';
} else {
$data = array('upload_data' => $this -> upload -> data());
$post_image = $_FILES['userfile']['name'];
}
// This is the check for new file is upload or not
if ( isset($_FILES['userfile']['name']) && $_FILES['userfile']['name'] != null )
{
// Use name field in do_upload method
if (!$this->upload->do_upload('userfile')) {
// If any problem in uploading
$errors = array('error' => $this->upload->display_errors());
} else {
$data = $this->upload->data();
// This is your new upload file name
$post_image = $data[ 'raw_name'].$data[ 'file_ext'];
}
}
else {
// This is your old file name if user not uploading new file
$post_image = $this->input->post('postimage');
}
Hope this code will help you to update your file
The upload library automatically increments files of the same name. If you previously uploaded my-pic.jpg and then uploaded the same file it would show up as my-pic1.jpg. Thus the filename is modified by the upload library.
You have to get the new filename via the function $this->upload->data() which returns a bunch of items related to your image upload.
https://www.codeigniter.com/user_guide/libraries/file_uploading.html#CI_Upload::data
You only have to replace $post_image = $_FILES['userfile']['name']; with $this->upload->data('file_name') or:
$file = $this->upload->data();
$post_image = $file['file_name']
Generally I recommend against using any user supplied name for a file. I would suggest using the $config['encrypt_name'] = true to get a randomized name. The above method would apply to this as well.

How to rename more than 1 file during upload ? Codeigniter

I have a form to upload about 5 files,
lets say it is a photo of the person who is registering and other document about him.
now i'm creating a folder for every registered user with their name ( btw, is it good thing to do? ), and i want to rename each file with the right name let say photo,document A,document B and etc.
my current code
$upload_setting['upload_path'] = './uploads/'.$_POST['name'].'/';
$upload_setting['allowed_types'] = 'jpg|pdf';
$upload_setting['max_size'] = 5000; // 5 MB
$upload_setting['file_name'] = $_POST['name']; // this define the uploaded file name
$this->load->library('upload', $upload_setting);
if ($this->form_validation->run() == FALSE){
$this->load->view('form');
}
else{
if (!is_dir('./uploads/'.$_POST['name'].'/')) {
mkdir('./uploads/'.$_POST['name'].'/', 0777, TRUE);
}
$this->member->register($this->input->post(NULL, TRUE));
$this->upload->do_upload('photo');
$this->upload->do_upload('document-A');
$this->upload->do_upload('document-B');
Also how can i let them free to upload JPG,PDF,DOC ?
i have to link these file in their profile page.
how can i know what extension they upload for each document ?
Please let me know if you have any suggestion or best practice to do this upload and then display each upload in their profile.
Thanks
To know the extension of your file you can use-
$newname= "name";
$path_parts = pathinfo($_FILES["picture"]["name"]);
$file_newname = $newname.'.'.$path_parts['extension'];
To Upload-
if( $_FILES['picture']['name'] )
{
$config['upload_path'] = 'images/receipt/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['file_name'] = $file_newname; //Here your file is being renamed
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('picture'))
{
$error = array('error' => $this->upload->display_errors());
return false;
}
}

uploading .ini files in CI

I get following error when trying to upload .ini files
"The filetype you are attempting to upload is not allowed."
Below is the function for uploading files
private function _upload_config_file() {
$config['upload_path'] = APPPATH . 'config/ini/';
$config['allowed_types'] = 'ini';
$config['max_size'] = '2000000';
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$this->upload_status = 'File uploaded succesfully !';
return true;
} else {
$this->upload_status = $this->upload->display_errors();
return false;
}
}
In View
$upload_file_attr = array(
'name' => 'userfile',
'id' => 'userfile',
'disabled' => 'disabled'
);
echo form_open_multipart('sys_setting', $form_sys_setting_multi);
echo form_label('Configure Manually' . form_checkbox($upload_checkbox, '', FALSE, $js_checkbox));
echo form_button($download_button);
echo form_upload($upload_file_attr);
echo form_reset($upload_reset);
echo form_submit($upload_submit);
echo form_close();
Is there any changes to be made in php.ini for uploading .ini files ?
Or Is it codeigniter's upload library that doesn't allow to upload .ini files ?
Need suggestions to solve this issue.
you forgot to put the field_name
Try adding this:
if ($this->upload->do_upload('userfile')) { //parameter should the your input file name attribute
$this->upload_status = 'File uploaded succesfully !';
return true;
} else {
$this->upload_status = $this->upload->display_errors();
return false;
}
I got this issue solved.In config/mimes.php modified $mimes array
$mimes = array('ini' => 'application/octet-stream')
If any one knows how to solve this issue without modifying the core files, *Please do comment.*

CodeIgniter Image Upload (Insert blank into array)

The form I'm working with contains info for five people. Optionally, the user can upload a photo for each of the five people. I'm attempting to insert a default image into the resulting array $files where an image is not uploaded. Help would be greatly appreciated.
function multiple_upload($upload_dir = APPPATH, $config = array())
{
$CI =& get_instance();
$files = array();
if(empty($config))
{
$config['upload_path'] = realpath($upload_dir . '/uploads');
$config['allowed_types'] = 'gif|jpg|jpeg|jpe|png';
$config['max_size'] = '2048';
}
$CI->load->library('upload', $config);
$errors = FALSE;
$this->load->library('image_lib'); // moved outside loop so it'll work
foreach($_FILES as $key => $value)
{
if( ! empty($value['name']))
{
if( ! $CI->upload->do_upload($key))
{
$data['upload_message'] = $CI->upload->display_errors(ERR_OPEN, ERR_CLOSE); // ERR_OPEN and ERR_CLOSE are error delimiters defined in a config file
$CI->load->vars($data);
$errors = TRUE;
}
else
{
// resize the saved image
$path = $CI->upload->data('full_path');
//echo $path['full_path'] . "<Br/>";
$config = array(
'source_image' => $path['full_path'],
'new_image' => $upload_dir . 'uploads/thumbs',
'maintain_ration' => true,
'width' => 150,
'height' => 150
);
$this->image_lib->initialize($config);
$this->image_lib->resize();
// Build a file array from all uploaded files
$files[] = $CI->upload->data();
}
}
}
// There was errors, we have to delete the uploaded files
if($errors)
{
foreach($files as $key => $file)
{
#unlink($file['full_path']);
}
}
elseif(empty($files) AND empty($data['upload_message']))
{
$CI->lang->load('upload');
$data['upload_message'] = ERR_OPEN.$CI->lang->line('upload_no_file_selected').ERR_CLOSE;
$CI->load->vars($data);
}
else
{
return $files;
}
}
It might be easier to do your check after you validate the uploaded files.
For example: Initialize an array with five empty elements, one for each picture, then for each file that's uploaded, set its filename to the appropriate array element. When you're done, just run through and for any empty elements, just tack in the file (or file path) to your default image.
This way, you keep your file uploading and validation as vanilla as possible, and deal with the business logic of your page separately.

Categories