Error while uploading Image and image name in database, codeigniter - codeigniter

There is an error while uploading an image in Codeigniter. The file name noimage is saved in the database.
// Upload Image Controller
$config['upload_path'] = './assets/Images/profilepictures';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048';
$config['max_width'] = '2000';
$config['max_height'] = '2000';
$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->m_user->profilepicture($post_image);
if($data['user']->profile_pic==null)
{
redirect(base_url().'user/profilepicture/');
}
Model
public function profilepicture($post_image){
$userID = $this->session->userdata("user_id");
$data = array(
'profile_pic' => $post_image,
);
$this->db->where('user_id', $userID);
$this->db->update('users', $data);
}

Your Image Name is not inserting in the database, because in your update query, you have not passed the $userID value.
Changes in Model =>
public function profilepicture($userID,$post_image) //Pass $userID here from Controller.
{
$data = array(
'profile_pic' => $post_image,
);
$this->db->where('user_id', $userID);
$this->db->update('users', $data);
}
Changes in Controller =>
$userID = $data['user']->user_id; //Add this line.
$this->m_user->profilepicture($userID,$post_image); //Update here
Your page is redirected because profile_pic is always null as it isn't updated in database. So after you successfully insert profile_pic in your database, your page will not redirected to redirect(base_url().'user/profilepicture/');.

When the image is not uploading try to redirect back to the form and don't add noimage.jpg to database
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
//Redirect to form with error message
} else {
//Get image name like this
$data = $this->upload->data();
$post_image = $data['file_name'];
//Call model function only when image successfully uploaded
$this->m_user->profilepicture($post_image);
}
Call model function only when image successfully uploaded
So, remove this condition if($data['user']->profile_pic==null)

Related

Codeigniter 3 application bug: converting title to slug does not work if there are diacritics in the title

I am working on a basic blog application with Codeigniter 3.1.8 and Bootstrap 4.
The single post URL is made from the post's title with url_title($this->input->post('title'), 'dash', TRUE). The entire post crearing function is this:
public function create() {
// Only logged in users can create posts
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$data = $this->get_data();
$data['tagline'] = "Add New Post";
if ($data['categories']) {
foreach ($data['categories'] as &$category) {
$category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
}
}
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('desc', 'Short description', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
if($this->form_validation->run() === FALSE){
$this->load->view('partials/header', $data);
$this->load->view('dashboard/create-post');
$this->load->view('partials/footer');
} else {
// Create slug (from title)
$slug = url_title($this->input->post('title'), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug, null);
if ($slugcount > 0) {
$slug = $slug."-".$slugcount;
}
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
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->Posts_model->create_post($post_image, $slug);
$this->session->set_flashdata('post_created', 'Your post has been created');
redirect('/');
}
}
I was convinced it worked fine, until I added a post that had diacritics in its title. "La mulți ani România!" results in the slug la-mul??i-ani-rom??nia instead of la-multi-ani-romania.
I tried to fix thos issues with Codeigniter's convert_accented_characters():
$slug = convert_accented_characters(url_title($this->input->post('title'), 'dash', TRUE));
It does not work even thou I did load the test helper:
$autoload['helper'] = array('url', 'form', 'date', 'text');
What other options do I have? How can I fix this problem?
The order in which I used the url_title() and convert_accented_characters() was wrong.
This is the correct one:
$slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
It works fine now.

How to remove existing file when uploading new one in codeigniter file uploading?

I am using codeigniter file uploading class to upload files and images in my local folder.I am using the code below, it's working fine.
public function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf|txt|sql';
$config['max_size'] = 8048000;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('Emp_details_view', $error);
}
else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
Now, my question is how to remove previously added file when uploading new one.
You can use unlink() function to delete your previous image
unlink('image-path/image-name');
first save your filename in a database table then when unlinking take that value from database and unlink. here uploads is the foldername .
unlink("uploads/".$val['image']);
$val['image'] contains imagename from db.

How to upload image in CodeIgniter?

In view
<?php echo form_open_multipart('welcome/do_upload');?>
<input type="file" name="userfile" size="20" />
In controler
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['overwrite'] = TRUE;
$config['encrypt_name'] = FALSE;
$config['remove_spaces'] = TRUE;
if ( ! is_dir($config['upload_path']) ) die("THE UPLOAD DIRECTORY DOES NOT EXIST");
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')) {
echo 'error';
} else {
return array('upload_data' => $this->upload->data());
}
}
And I call this function like this
$this->data['data'] = $this->do_upload();
and view this image:
<ul>
<?php foreach ($data['upload_data'] as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
I don't know what's the error.
It seems the problem is you send the form request to welcome/do_upload, and call the Welcome::do_upload() method in another one by $this->do_upload().
Hence when you call the $this->do_upload(); within your second method, the $_FILES array would be empty.
And that's why var_dump($data['upload_data']); returns NULL.
If you want to upload the file from welcome/second_method, send the form request to the welcome/second_method where you call $this->do_upload();.
Then change the form helper function (within the View) as follows1:
// Change the 'second_method' to your method name
echo form_open_multipart('welcome/second_method');
File Uploading with CodeIgniter
CodeIgniter has documented the Uploading process very well, by using the File Uploading library.
You could take a look at the sample code in the user guide; And also, in order to get a better understanding of the uploading configs, Check the Config items Explanation section at the end of the manual page.
Also there are couple of articles/samples about the file uploading in CodeIgniter, you might want to consider:
http://code.tutsplus.com/tutorials/how-to-upload-files-with-codeigniter-and-ajax--net-21684
http://runnable.com/UhIc93EfFJEMAADX/how-to-upload-file-in-codeigniter
http://jamshidhashimi.com/image-upload-with-codeigniter-2/
http://code.tutsplus.com/tutorials/how-to-upload-files-with-codeigniter-and-ajax--net-21684
http://hashem.ir/CodeIgniter/libraries/file_uploading.html (CodeIgniter 3.0-dev User Guide)
Just as a side-note: Make sure that you've loaded the url and form helper functions before using the CodeIgniter sample code:
// Load the helper files within the Controller
$this->load->helper('form');
$this->load->helper('url');
// Load the helper files within the application/config/autoload
$autoload['helper'] = array('form', 'url');
1. The form must be "multipart" type for file uploading. Hence you should use `form_open_multipart()` helper function which returns:
``
Simple Image upload in codeigniter
Find below code for easy image upload:
public function doupload()
{
$upload_path="https://localhost/project/profile"
$uid='10'; //creare seperate folder for each user
$upPath=upload_path."/".$uid;
if(!file_exists($upPath))
{
mkdir($upPath, 0777, true);
}
$config = array(
'upload_path' => $upPath,
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('userpic'))
{
$data['imageError'] = $this->upload->display_errors();
}
else
{
$imageDetailArray = $this->upload->data();
$image = $imageDetailArray['file_name'];
}
}
//this is the code you have to use in you controller
$config['upload_path'] = './uploads/';
// directory (http://localhost/codeigniter/index.php/your directory)
$config['allowed_types'] = 'gif|jpg|png|jpeg';
//Image type
$config['max_size'] = 0;
// I have chosen max size no limit
$new_name = time() . '-' . $_FILES["txt_file"]['name'];
//Added time function in image name for no duplicate image
$config['file_name'] = $new_name;
//Stored the new name into $config['file_name']
$this->load->library('upload', $config);
if (!$this->upload->do_upload() && !empty($_FILES['txt_file']['name'])) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('production/create_images', $error);
} else {
$upload_data = $this->upload->data();
}
Change the code like this. It works perfectly:
public function uploadImageFile() //gallery insert
{
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$new_image_name = time() . str_replace(str_split(' ()\\/,:*?"<>|'), '',
$_FILES['image_file']['name']);
$config['upload_path'] = 'uploads/gallery/';
$config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
$config['file_name'] = $new_image_name;
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$config['$min_width'] = '0';
$config['min_height'] = '0';
$this->load->library('upload', $config);
$upload = $this->upload->do_upload('image_file');
$title=$this->input->post('title');
$value=array('title'=>$title,'image_name'=>
$new_image_name,'crop_name'=>$crop_image_name);}
$image_folder = APPPATH . "../images/owner_profile/" . $_POST ['mob_no'] [0] . $na;
if (isset ( $_FILES ['image'] ) && $_FILES ['image'] ['error'] == 0) {
list ( $a, $b ) = explode ( '.', $_FILES ['image'] ['name'] );
$b = end ( explode ( '.', $_FILES ['image'] ['name'] ) );
$up = move_uploaded_file ( $_FILES ['image'] ['tmp_name'], $image_folder . "." . $b );
$path = ($_POST ['mob_no'] [0] . $na . "." . $b);
Below code for an uploading a single file at a time.
This is correct and perfect to upload a single file.
Read all commented instructions and follow the code.
Definitely, it is worked.
public function upload_file() {
***// Upload folder location***
$config['upload_path'] = './public/upload/';
***// Allowed file type***
$config['allowed_types'] = 'jpg|jpeg|png|pdf';
***// Max size, i will set 2MB***
$config['max_size'] = '2024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
***// load upload library***
$this->load->library('upload', $config);
***// do_upload is the method, to send the particular image and file on that
// particular
// location that is detail in $config['upload_path'].
// In bracks will set name upload, here you need to set input name attribute
// value.***
if($this->upload->do_upload('upload')) {
$data = $this->upload->data();
$post['upload'] = $data['file_name'];
} else {
$error = array('error' => $this->upload->display_errors());
}
}
check $this->upload->initialize($config); this works fine for me
$new_image_name = "imgName".time() . str_replace(str_split(' ()\\/,:*?"<>|'), '',
$_FILES['userfile']['name']);
$config = array();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
$config['file_name'] = $new_image_name;
$config['max_size'] = '0';
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|mp4|jpeg';
$config['file_name'] = url_title("imgsclogo");
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
$this->upload->initialize($config);
$this->upload->do_upload();
$data = $this->upload->data();
}

codeigniter uploading image from form

I have a field of my form (which is uploading personal picture). So the user selects image from pc and submit the form. I am later on handling all posted data via:
$this->input->post()
My method for insertion into database is:
public function add_user()
{
$data = array(
'membership'=>$this->input->post('membership_type'),
'fullname'=>$this->input->post('fullname'),
'username'=>$this->input->post('username'),
'password'=>md5($this->input->post('password')),
'email'=>$this->input->post('email'),
'city'=>$this->input->post('city'));
'profilepic'=>$this->input->post('profilepic'));
$this->db->insert('members',$data);
}
Now what I want to insert in the profilepic field is the path to the image on the server. I know am doing it wrong above because this way am inserting the picture posted to profilepic. I need some correction please. Is there a function that can perform upload and return the path? but again how can I associate the upload of picture with upload of user data?
Regards,
EDIT: Tried the code provided below and got this:
A PHP Error was encountered
Severity: Notice
Message: Use of undefined constant full_path - assumed 'full_path'
Filename: models/membership_model.php
Line Number: 29
A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by
(output started at
/home2/xsysdeve/public_html/system/core/Exceptions.php:185)
Filename: core/Common.php
Line Number: 438
Please try this one:
public function add_user()
{
$config['upload_path'] = '/file_path/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->load->library('upload', $config);
$this->upload->do_upload('profilepic');
$data_upload_files = $this->upload->data();
$image = $data_upload_files[full_path];
$data = array(
'membership'=>$this->input->post('membership_type'),
'fullname'=>$this->input->post('fullname'),
'username'=>$this->input->post('username'),
'password'=>md5($this->input->post('password')),
'email'=>$this->input->post('email'),
'city'=>$this->input->post('city'));
'profilepic'=>$image;
$this->db->insert('members',$data);
}
For more information visit this link: http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
You can also try using 2 CI functions and check for the POST of the textual data as well as the image validation:
class SomeForm extends CI_Controller{
function add_user() //this function is your form
{
$this->load->view('templates/header');
$this->load->view('new_form_entry', array('error' => ' ' ));
$this->load->view('templates/footer');
}
function add_user_status() //this function is your form processing
{
$config['upload_path'] = './assets/images';
$config['allowed_types'] = 'gif|jpg|png';
//$config['max_size'] = '2000';
//$config['max_width'] = '340';
//$config['max_height'] = '190';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
//check for errors with the upload
$error = array('error' => $this->upload->display_errors());
$this->load->view('templates/header');
$this->load->view('new_form_entry', $error);
$this->load->view('templates/footer');
}
else
{
//upload the new image
$upload_data = $this->upload->data();
$image_name = $upload_data['file_name'];
if($_POST){
$data = array(
'author'=>$_POST['author'],
'name'=>$_POST['name'],
'image_thumb'=>'../assets/images/'.$image_name,
'video'=>$_POST['video'],
'title'=>$_POST['title'],
'body'=>$_POST['body'],
'created' => date('Y-m-d H:i:s')
);
//insert the new post
$this->your_database_model_name->insert_entry($data);
}
redirect(base_url().'SomeForm/index');
}
}
}

How to output uploading errors as flashdata - CodeIgniter

I'm wanting to display any errors produced while uploading a file by redirecting the user back to the same page they used to upload the file. The thing is that I pre-populate some inputs on that page, so I can't use redirect(controller/method_to_load_page) as that wouldn't carry out the data population.
Using $this->load->view('add_page',$error); won't work either (the way that I'm using it), because although that will show the errors, it won't show the input fields with the pre-populated data.
This is the method in my controller which loads the form to upload a file and other fields:
public function add_products_page()
{
//get each categories subcategory and place them in their own variable
$data['categories1'] = $this->admin_model->getSubcategories('1');
$data['error'] = '';
$this->load->view('add_page',$data);
}
And from that page, the user can fill in the form and choose an image. The form will then be submitted to this method in the same controller:
public function add_book()
{
$id = $this->admin_model->add_book();
$config['file_name'] = $id;
$config['upload_path'] = './images/';
$config['allowed_types'] = 'jpg';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('add_page', $error);
}
else
{
redirect('admin/add_products_page', 'refresh');
}
}
If there are no errors, the redirect to add_products_page() method is okay, however when there's an error, the view 'add_page' is loaded and the errors are shown, but my pre-populated field isn't populated anymore because the method to do that isn't being called.
So I really would like to know how I can both load my view by calling the method add_products_page to populate my input fields, and also show errors when they occur. Please if someone could help I would appreciate it greatly.
Why post to a different method and then redirect? You can handle it all in the same method.
public function add_products_page()
{
if ($this->input->server('REQUEST_METHOD') == 'POST')
{
$result = $this->_add_book();
if ($result['is_error'])
{
// TODO: whatever it takes to show an error message
$data['error'] = $result['message'];
}
else
{
// TODO: whatever it takes to show a success message
$data['error'] = '';
}
}
//get each categories subcategory and place them in their own variable
$data['categories1'] = $this->admin_model->getSubcategories('1');
$this->load->view('add_page',$data);
}
public function _add_book() // add underscore so it's not directly accessible
{
$result = array(
'is_error' => TRUE,
'message' => '',
);
$id = $this->admin_model->add_book();
$config['file_name'] = $id;
$config['upload_path'] = './images/';
$config['allowed_types'] = 'jpg';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
// set an error message
$result['message'] = $error;
}
else
{
// set a success message
$result['is_error'] = FALSE;
$result['message'] = 'SOME SUCCESS MSG';
}
return $result;
}

Resources