Codeigniter replace uploaded image - php

I'm using Codeigniter's File Uploading Class for uploading user avatars. Is there a way to replace a user's image file whenever he/she uploads a new one? I want to replace an existing avatar with the newest one uploaded.
My image uploading controller
function upload_avatar()
{
$config['upload_path'] = './uploads/avatars/';
$config['allowed_types'] = 'jpg|png';
$config['overwrite'] = FALSE; //overwrite user avatar
$config['encrypt_name'] = TRUE;
$config['max_size'] = '200'; //in KB
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = $this->upload->display_errors();
$this->session->set_flashdata('error', $error);
redirect('/settings/avatar');
}
else
{
$config['image_library'] = 'gd2';
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = FALSE;
$config['width'] = 120;
$config['height'] = 120;
$this->load->library('image_lib', $config);
$this->image_lib->crop();
//Add image path to database
$avatar_path = 'uploads/avatars/' . $this->upload->file_name;
$user_id = $this->tank_auth->get_user_id();
$this->Settings_model->update_avatar($avatar_path, $user_id);
$this->session->set_flashdata('success', 'Avatar updated!');
redirect('/settings/avatar');
}
}

There is a public attribute overwrite that dictates the decision to overwrite the original file. By default, a new filename is created based on the original. Here's the source from Upload.php in CI:
/*
* Validate the file name
* This function appends an number onto the end of
* the file if one with the same name already exists.
* If it returns false there was a problem.
*/
$this->orig_name = $this->file_name;
if ($this->overwrite == FALSE)
{
$this->file_name = $this->set_filename($this->upload_path, $this->file_name);
if ($this->file_name === FALSE)
{
return FALSE;
}
}
So all you need to do to get the overwrite working is:
$this->load->library('upload', $config);
$this->upload->overwrite = true;

Simple set "overide" be true in your config.
$this->upload->initialize(array(
"upload_path"=>$path,
"allowed_types"=>"jpg|png|jpeg",
"overwrite"=>true
));

did you try to change
$config['overwrite'] = FALSE;
to
$config['overwrite'] = TRUE;

Related

Resize images in codeginiter

currently I'm working with codeigniter framework but I'm confused how to resize the image. I have followed the documentation but I'm still confused. This is my code
public function create(){
//Check login
if(!$this->session->userdata('logged_in')){
redirect('users/login');
}
$data['title'] = 'Create Post';
$data['categories'] = $this->BlogModel->get_categories();
$this->form_validation->set_rules('title','title','required');
$this->form_validation->set_rules('content','content','required');
if($this->form_validation->run() === FALSE){
$this->load->view('frontend/header');
$this->load->view('frontend/navbar');
$this->load->view('frontend/blog/create',$data);
$this->load->view('frontend/footer');
} else{
//Upload Image
$config['upload_path'] = './assets/images/posts/blog';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'noimage.jpg';
}else{
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->BlogModel->create_post($post_image);
//set message
$this->session->set_flashdata('post_created','Your post has been created');
redirect('blog');
}
}
Please advice how to resize the image.
Thanks!
If you want to do different things like resize the original image directly, rather than creating a thumb set create_thumb to false, and do not use new_image. The only difference between create_thumb and new_image is that new_image allows you to specify your own path and name. Whereas the most you can do with create_thumb is change the thumb_marker. Which is all in the docs...
//Upload Image
$config['upload_path'] = './assets/images/posts/blog';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
//$errors = array('error' => $this->upload->display_errors());
exit($this->upload->display_errors());
$post_image = 'noimage.jpg';
} else {
$up_data = $this->upload->data();
$post_image = $up_data['name'];
$config = array(); // clear prev config
$config['image_library'] = 'gd2';
$config['source_image'] = $up_data['full_path'];
$config['create_thumb'] = TRUE;
$config['thumb_marker'] = '_thumbnail';
$config['maintain_ratio'] = TRUE;
$config['width'] = 75;
$config['height'] = 50;
$this->load->library('image_lib', $config);
if(!$this->image_lib->resize()) {
exit($this->image_lib->display_errors());
}
$thumb_path = $up_data['file_path'] . $up_data['raw_name'] . $config['thumb_marker'] . $up_data['file_ext'];
}
The exits you can remove later, but leave them for debugging until you figure out a way to properly message your errors (I suggest session vars). These functions should also be moved to a model.

Codeigniter - Two images upload did not work

I tried to upload two images using a form. To do that I wrote a image function.
protected function imageUploadResize($filename, $field_name, $width, $height, $maker){
// thumb image upload settings
$config['upload_path'] = './uploads/packages/';
$config['allowed_types'] = 'gif|jpg|png';
// thumb upload settings
$image_new_name = time().'_'.$filename;
$config['file_name'] = $image_new_name;
$this->load->library('upload', $config);
// upload thumb image
if ( $this->upload->do_upload($field_name)) {
// resize uploaded file
$config['image_library'] = 'gd2';
$config['source_image'] = './uploads/packages/'.$image_new_name;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = $width;
$config['height'] = $height;
$config['thumb_marker'] = $maker;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$error = array('error' => $this->upload->display_errors());
} else {
$imageData = array('upload_data' => $this->upload->data());
}
return $image_new_name;
}
And I access that function this way,
// allocate image name to data set
if(!empty($_FILES["thumb_image"]['name'])){
// thumb upload
$thumb_image_new_name = $this->imageUploadResize($_FILES["thumb_image"]['name'],'thumb_image',THUMB_IMAGE_WIDTH, THUMB_IMAGE_HEIGHT, '_thumb');
$data['thumb_image'] = $thumb_image_new_name;
}else{
$data['thumb_image'] = "";
}
// allocate image name to data set
if(!empty($_FILES["banner_image"]['name'])){
// banner upload
$banner_image_new_name = $this->imageUploadResize($_FILES["banner_image"]['name'],'banner_image',BANNER_IMAGE_WIDTH, BANNER_IMAGE_HEIGHT, '_banner');
$data['banner_image'] = $banner_image_new_name;
}else{
$data['banner_image'] = "";
}
When I upload one image (thumb_image or banner_image) above function is worked properly.
But when I upload both images thumb_image uploaded properly but banner_image did not upload properly. As a example assume I am going to upload Hydrangeas.jpg and Desert.jpg. Then it is working this way,
Then file uploaded this way (images names of the folder),
1493025280_Hydrangeas.jpg
1493025280_Hydrangeas_thumb.jpg
1493025280_Hydrangeas1.jpg - image name also wrong
But expected output is (images names of the folder),
1493025280_Hydrangeas.jpg
1493025280_Hydrangeas_thumb.jpg
1493025280_Desert.jpg
1493025280_Desert_banner.jpg
Can someone please help me, thank you..
A different approach that i use for file uploads is below.
I rearrange the $_FILES array because the original has some difficulties with keys and objects.
$files = array();
foreach ($_FILES['files']['name'] as $num_key => $dummy) {
foreach ($_FILES['files'] as $txt_key => $dummy) {
$files[$num_key][$txt_key] = $_FILES['files'][$txt_key][$num_key];
}
}
In new array, loop through each image and do what you need:
foreach ($files as $file) {
if ($file['error'] == 0) {
//Your code here...
//Call your function imageUploadResize
}
}
Finally found the solution, In codeigniter when upload image, we have to call,
$this->load->library('upload', $config);
Then we have to initialized the configurations.
$this->upload->initialize($config);
And when resize image we have to call,
$this->load->library('image_lib', $config);
Then have to initialized the configurations.
$this->image_lib->initialize($config);
Therefore completed function is,
protected function imageUploadResize($filename, $field_name, $width, $height, $maker){
// thumb image upload settings
$config['upload_path'] = './uploads/packages/';
$config['allowed_types'] = 'gif|jpg|png';
// thumb upload settings
$image_new_name = time().'_'.$filename;
$config['file_name'] = $image_new_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
// upload thumb image
if ( $this->upload->do_upload($field_name)) {
// resize uploaded file
$config['image_library'] = 'gd2';
$config['source_image'] = './uploads/packages/'.$image_new_name;
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = $width;
$config['height'] = $height;
$config['thumb_marker'] = $maker;
$this->load->library('image_lib', $config);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$error = array('error' => $this->upload->display_errors());
} else {
$imageData = array('upload_data' => $this->upload->data());
}
return $image_new_name;
}

Codeigniter validate_upload library can't upload file

I was referred to #raheel shan's thread on this page and use this My_Upload extended library to have if(!$this->upload->validate_upload('photo')) validation of input file, the validation is work fine if user try to upload invalid file type and the message is just shown in the right place.
Somehow, I can't upload image file to its folder and the filename is unable to save into table, there was works pretty to upload the image file and saved to table before I use this library.
Can someone please help with figure what's wrong in my code?
Controller:
public function index()
{
if(!$this->tank_auth->is_logged_in()) {
redirect('/auth/login');
}else{
$user_id = $this->session->userdata('user_id');
$profile = $this->users->get_profile_by_id($user_id);
$checked = $this->input->post('remove');
$this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean|min_length[5]|max_length[30]');
$this->form_validation->set_rules('country', 'Country', 'trim|required|xss_clean');
$this->form_validation->set_rules('website', 'Website', 'trim|xss_clean|max_length[30]');
if(isset($_FILES['photo']) AND !empty($_FILES['photo']['name'])) {
$this->form_validation->set_rules('photo', 'Photo', 'trim|callback_valid_upload');
if($this->upload->do_upload('photo')){
// image resizing
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['maintain_ratio'] = TRUE;
$config['width'] = 100;
$config['height'] = 100;
$this->load->library('image_lib', $config); //codeigniter default function
if(!$this->image_lib->resize()){
$this->session->set_flashdata('upload_msg', $this->image_lib->display_errors());
}else{
$image_data = $this->upload->data();
$photo_to_table = $image_data['file_name'];
}
}
}else{
if((int) $checked == 1){
unlink('./uploads/'.$profile->photo);
$photo_to_table = '';
}else{
$photo_to_table = $profile->photo;
}
//$photo_to_table = ((int) $checked == 1) ? '' : $profile->photo;
}
if($this->form_validation->run()) { // validation ok
if(!is_null($data = $this->tank_auth->update_user(
$this->form_validation->set_value('name'),
$this->form_validation->set_value('country'),
$this->form_validation->set_value('website'),
$photo_to_table
))) { // success
$this->session->set_flashdata('msg', 'Profile has been updated');
redirect(current_url());
}
}else{
$errors = $this->tank_auth->get_error_message();
foreach($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
//blah blah..//load view
}
public function valid_upload()
{
$user_id = $this->session->userdata('user_id');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '500';
$config['file_name'] = $user_id.'_'.strtotime('now');
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
//$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->validate_upload('photo'))
{
$this->form_validation->set_message('valid_upload', $this->upload->display_errors());
return FALSE;
}else{
return TRUE;
}
}
}
Thanks.
I had a similar problem and in my case it was because I chose the wrong image library. Check your PHP installation for the appropriate image library you wish to use and make sure it matches. By default, CodeIgniter chooses GD2 (GD library versions >= 2) as the default image library.
http://ellislab.com/codeigniter/user-guide/libraries/image_lib.html
Try this:
// image resizing
$config['image_library'] = 'gd'; // specify the correct image library
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['maintain_ratio'] = TRUE;
$config['width'] = 100;
$config['height'] = 100;
What is your result in
$this->image_lib->display_errors()
Is your upload directory writable?
Do you have GD installed and active in php? Maybe try GD as Mahmoud suggested?

How to make a user upload folder and display specific content in codeigniter?

I am trying to create an upload folder for each user on my site, and display their photos in a specific area. I have been able to get the codeigniter upload helper to work and can upload files to a folder. Now I want to be able to:
have the photos upload by a specific user be placed in a folder for that user created on the fly specific to their id
auto size the photo for two sizes. A thumbnail and a larger size
I think I have it set up from research on how to do those things I just don't know how to plug in their id's syntactically as well as creating a folder and uploading it.
the last step would be displaying these photos in the locations of my choice tied to their ids.
Here is my controller
public function upload()
{
mkdir('./upload/' . $this->session->userdata('id'), 0777);
$config['image_library'] = 'gd2';
$config['source_image'] = 'PATH TO FOLDER??';
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 75;
$config['height'] = 50;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$data['main_content'] = 'account/upload';
$this->load->view('includes/templates/main_page_template', $data);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
You're creating the users directory but not setting it as the upload path...
$user_folder = './upload/' . $this->session->userdata('id');
if(!is_dir($user_folder)){
mkdir($user_folder, 0777);
}
...
$config['upload_path'] = $user_folder;
....

Failed to create thumb image in $_FILES loop

I iterate through $_FILES to create thumb images of uploaded pictures. It works fine for the first image but fails for the following pictures. Do I miss to add a special line or there is flow in my code?
Note: Original files gets uploaded successfully and exist in folder before creating thumb out of them.
When I echo error, I get this: "Your server does not support the GD function required to process this type of image.". When I upload it on its own, it works!!!!
Thanks
public function upload_image()
{
$config['upload_path'] = './web/uploads/images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5120;
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['encrypt_name'] = true;
$this->load->library('upload');
$this->upload->initialize($config);
foreach ($_FILES as $file => $value)
{
$this->upload->do_upload($file);
$result = $this->upload->data();
if ($this->manipulate_image($result['file_name']) === false)
{
echo 'Failed to create thumb for the image ' . $value['name'] . '<br />';
}
}
}
public function manipulate_image($file_name)
{
$config['image_library'] = 'gd2';
$config['source_image'] = './web/uploads/images/' . $file_name;
$config['create_thumb'] = true;
$config['maintain_ratio'] = false;
$config['width'] = 100;
$config['height'] = 100;
//$config['master_dim'] = 'width';
$config['thumb_marker'] = '_thumb';
$this->load->library('image_lib', $config);
if (! $this->image_lib->resize())
{
$this->image_lib->clear();
return false;
}
$this->image_lib->clear();
return true;
}
I see two things, first, I would move the load on the library outside of the foreach loop then use initialize inside the loop to set the config:
$this->image_lib->initialize($config);
Also, as documented here you can use
echo $this->image_lib->display_errors();
To get more insight on your problem
Apparently loading loading image_lib multiple times in a loop causes this problem.
Solved without including in loop.

Categories