Unlink function has not been successful with codeigniter - codeigniter

I want to delete the image long after I update the new image. I have added unlink(), but the old image is not deleted.
Controller :
public function Update()
{
$id = $this->input->post('id');
$name = $this->input->post('name');
if($_FILES['image']['name']!="")
{
$config['upload_path'] = './image/';
$config['allowed_types'] ='gif|jpg|png|jpeg|jpe|pdf|doc|docx|rtf|text|txt';
$this->load->library('upload', $config);
if($this->upload->do_upload('image')){
$uploadData = $this->upload->data();
$image = $uploadData['file_name'];
}else{
$image= '';
}
}else{
$image = '';
}
$data = array(
'name' => $name,
);
if($image != ''){
$data['image'] = $image;
unlink("./image/$row->file_name");
}
$this->model_user->update_user($data,$id);
}
Model :
public function update_user($data, $id)
{
$this->db->where('id', $id);
return $this->db->update('table_user', $data);
}

In your code, you are not getting old image name from DB
First, get the old image name and then try like this
if($image != ''){
$data['image'] = $image;
$oldimage = $this->model_user->get_oldimage($id);
unlink("path/to/directory/".$oldimage);
}
Model
public function get_oldimage($id){
return $this->db->get_where('table_user', ['id' => $id])->row()->image;
}

Related

Not able to insert image path into database in codeigniter

class Stud_controller extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->helper('url');
$this->load->database();
}
public function index()
{
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->helper('url');
$this->load->view('Stud_view',$data);
}
public function add_student_view()
{
$this->load->helper('form');
$this->load->view('Stud_add');
}
public function add_student()
{
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->model('Stud_Model');
//$this->load->library('upload', $config);
$config['upload_path'] = './uploads/';
$target_file['image'] = $config['upload_path'] . basename($_FILES["fileToUpload"]["name"]);
$config['allowed_types'] = 'gif|jpg|jpeg|png|pdf|doc';
$config['max_size'] = 1000;
$config['max_width'] = 1300;
$config['max_height'] = 1024;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('fileToUpload'))
{
echo "fail";
//$this->load->view('upload', $error);
}
else
{
echo "success";
echo $target_file['image'] ;
//$QueryInsertFile="INSERT INTO stud SET image='$target_file'";
// $this->load->view('success', $data);
}
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name'),
$target_file['image'] =>$data['image']
);
$this->Stud_Model->insert($data);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function update_student_view(){
$this->load->helper('form');
$roll_no = $this->uri->segment('3');
$query = $this->db->get_where("stud",array("roll_no"=>$roll_no));
$data['records'] = $query->result();
$data['old_roll_no'] = $roll_no;
$this->load->view('Stud_edit',$data);
}
public function update_student(){
$this->load->model('Stud_Model');
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name')
);
$old_roll_no = $this->input->post('old_roll_no');
$this->Stud_Model->update($data,$old_roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function delete_student(){
$this->load->model('Stud_Model');
$roll_no = $this->uri->segment('3');
$this->Stud_Model->delete($roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
}
this line is error
$target_file['image'] =>$data['image']
replace into
'image'=>$_target_file['image]

How to use Multiple images in codeigniter

In my page I want user to select multiple images and upload it I am saving images name in database for reference. I am successful in uploading single images in database and can also show image in view but now I have problem in uploading multiple images.
public function add_record()
{
$this->form_validation->set_rules('category', 'category', 'required');
$current_date = date("Y-m-d H:i:s");
$error='';
if($this->form_validation->run())
{
$image = '';
if($_FILES['image']['name'])
{
if (!is_dir('/backend_assets/media/image/')) {
mkdir('./backend_assets/media/image/', 0777, TRUE);
}
$config['upload_path'] = './backend_assets/media/image/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ($this->upload->do_upload('image'))
{
$data = $this->upload->data();
$image = $data['file_name'];
}else{
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect(base_url('admin/image'));
}
}
$insert_array = array(
'gl_cat_id' => $this->input->post('category'),
'gl_image'=> $image
);
if ($this->common_model->add_records('vm_image',$insert_array))
{
$id = $this->db->insert_id();
$insert_sco_details = array(
'sd_ty'=>'vm_image',
'sd_ty_id'=>$id,
'sd_image'=>$image
);
if($this->common_model->publication('vm_image',$id) && $this->common_model->add_records('vm_seo_detail',$insert_sco_details))
{
$this->session->set_flashdata('success','Record added successfully');
redirect(base_url('admin/image'));
}else{
$this->session->set_flashdata('error','Error while adding record');
redirect(base_url('admin/image'));
}
}else{
$this->session->set_flashdata('error','Error while adding record');
redirect(base_url('admin/image'));
}
}
$where_array = array('vm_publications.status !=' => 4);
$data['users_type'] = $this->common_model->get_records('vm_image_category','','','');
$data['include'] = 'backend/image/add_image';
$this->load->view('backend/container', $data);
}
How is it possible with above code...?
$current_date = date("Y-m-d H:i:s");
$error = '';
$image = '';
if(isset($_FILES['image']['name']))
{
//print_r($_FILES);
$id = base64_decode($this->input->post('gid'));
$filesCount = count($_FILES['image']['name']);
$inserted = '';
for($i = 0; $i < $filesCount; $i++)
{
$_FILES['userFile']['name'] = $_FILES['image']['name'][$i];
$_FILES['userFile']['type'] = $_FILES['image']['type'][$i];
$_FILES['userFile']['tmp_name'] = $_FILES['image']['tmp_name'][$i];
$_FILES['userFile']['error'] = $_FILES['image']['error'][$i];
$_FILES['userFile']['size'] = $_FILES['image']['size'][$i];
$config['upload_path'] = './backend_assets/media/image/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('userFile'))
{
$fileData = $this->upload->data();
$image = $fileData['file_name'];
$insert_array = array(
'gl_cat_id' => $this->input->post('category'),
'gl_image'=> $image
);
if ($this->common_model->add_records('vm_image',$insert_array))
{
$id = $this->db->insert_id();
$insert_sco_details = array(
'sd_ty'=>'vm_image',
'sd_ty_id'=>$id,
'sd_image'=>$image
);
if($this->common_model->publication('vm_image',$id) && $this->common_model->add_records('vm_seo_detail',$insert_sco_details))
{
$inserted++;
}
}
}
}
if($inserted == $filesCount)
{ $this->session->set_flashdata('success','Images uploaded successfully');
redirect(base_url('adminp8AamG6ueHFNGAAp/image'));
}else{
$this->session->set_flashdata('error','Error while adding record');
redirect(base_url('adminp8AamG6ueHFNGAAp/image'));
}
}
$where_array = array('vm_publications.status !=' => 4);
$data['users_type'] = $this->common_model->get_records('vm_image_category','','','');
$data['include'] = 'backend/image/add_image';
$this->load->view('backend/container', $data);
try below code in you add_record() function. it will helpful to you. few days ago, i have faced same problem
$files = $_FILES;
$count = count($_FILES['image']['name']);
for($i=0; $i<$count; $i++) {
$_FILES['image']['name']= $files['image']['name'][$i];
$_FILES['image']['type']= $files['image']['type'][$i];
$_FILES['image']['tmp_name']= $files['image']['tmp_name'][$i];
$_FILES['image']['error']= $files['image']['error'][$i];
$_FILES['image']['size']= $files['image']['size'][$i];
$this->upload->initialize($this->set_upload_options());//function defination below
$this->upload->do_upload('image');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name'];
$fileName = $upload_data['file_name'];
$images[] = $fileName;
}
$fileName = $images;
and set file upload configuration in set_upload_options function in same controller.
function set_upload_options() {
$config = array();
$config['upload_path'] = PATH;
$config['remove_spaces']=TRUE;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '78000';
return $config;
}
First, debug the output of the $_FILES variable. This should give you an array of files that are being uploaded. Loop through them to treat each one individually.
foreach ($_FILES as $file) {
// do some file processing on the $file object instead of $_FILES object.
// example: instead of using 'if($_FILES['image']['name'])'
// use: 'if($file['image']['name'])'
}
If you want to use CI's upload class, check out their Docs here: https://www.codeigniter.com/userguide3/libraries/file_uploading.html

how to do image upload in codeigniter?

I am trying to upload an image in root folder and its file name in database. here is what I did for the upload function:
public function add_blog($id=0){
if(!empty($_FILES['picture']['name'])){
$config['upload_path'] = 'uploads/blog_image';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
// print_r($value['name'][$s]);exit;
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
print_r($picture); exit;
}
}
print_r($config['file_name']); exit;
$data['blog_data']=array('blog_post'=>$this->input->post('blog_post'),
'posted_by'=>$this->input->post('posted_by'),
'blog_image'=>$picture);
if ($id==0){
$this->db->insert('blog',$data['blog_data']);
// $last_id = $this->db->insert_id();
}
else {
$this->db->where('id',$id);
// $last_id = $this->db->insert_id();
$this->db->update('blog',$data['blog_data']);
}
}
problem here is i am being able to insert other data except image. I get the image name with that print_r($config[file_name]) if i do print_r() and exit, if not it will just insert other data except image. But the image is neither uploaded in root folder nor its name in database. If I give the non existing upload path, then also its not throwing any error. I think code inside If is not executed. How can i solve this ? Thanks in advance.
private function _upload_image( ) {
$this->load->library( 'upload' );
if ($_FILES && $_FILES['picture']['name'] !== ""){
$config['upload_path'] = 'uploads/blog_image';
$config['allowed_types'] = 'jpg|jpeg|png|bmp';
$config['max_size'] = 10000;
/*the picture name must be unique, use function now()*/
$config['file_name'] = $_FILES['picture']['name'] . now();
$config['file_ext_tolower'] = TRUE;
$this->upload->initialize( $config );
if ( $this->upload->do_upload( 'picture' ) ){
$file_name = $this->upload->data()['file_name'];
$full_path = $this->upload->data()['full_path'];
/*If you want create a thumb, use this part*/
$this->load->library('image_lib');
$config = array(
'source_image' => $path,
'new_image' => $this->_image_path,
'maintain_ratio' => true,
'width' => 128,
'height' => 128,
'create_thumb' => TRUE,
'thumb_marker' => '_thumb',
);
$this->image_lib->initialize( $config );
$this->image_lib->resize();
/*Save in database*/
$this->db->insert('blog', [
'file_name' => $file_name,
'full_path' => $full_path
]);
} else {
//if picture is empty, do something
}
}
}
You do not need to use $_FILES && $_FILES ['picture']['name']! == "" only if your form has the picture field as an optional field, $this->upload->do_upload('picture') and get data from $this->upload->data(), read the manual
public function add_blog()
{
$config['upload_path'] = '.uploads/blog_image';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = 10000;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('picture'))
{//Do something with errors
$errors = $this->upload->display_errors();
}
else
{
$data = $this->upload->data();
$this->db->insert('blog', [
'file_name' => $data['file_name'],
'full_path' => $data['full_path']
]);
}
}
I just didn't mention the file size to be uploaded. I did this in my above code and worked.
EDIT
public function add_blog($id=0){
if(!empty($_FILES['picture']['name'])){
$config['upload_path'] = 'uploads/blog_image';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = 0;
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
// print_r($value['name'][$s]);exit;
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
// print_r($picture); exit;
}
}
// print_r($config['file_name']); exit;
$data['blog_data']=array('blog_post'=>$this->input->post('blog_post'),
'posted_by'=>$this->input->post('posted_by'),
'blog_image'=>$picture);
if ($id==0){
$this->db->insert('blog',$data['blog_data']);
// $last_id = $this->db->insert_id();
}
else {
$this->db->where('id',$id);
// $last_id = $this->db->insert_id();
$this->db->update('blog',$data['blog_data']);
}
}
And this code works for both insert and update.

Invalid argument supplied for foreach()

I do not understand how to fix this codes:
return $this->db->update('slideshow');
I have tried several codes like changing it to $query or $query_result etc. and the error still exist. I still have to use $this->db->update('');
controllers/Cuploadfile.php
function uploadedit()
{
$data['images'] = ''; // Need to place it here and get images here.
//set preferences
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|gif';
$config['max_size'] = '500000';
//load upload class library
$this->load->library('upload', $config);
$this->load->model('Mpages');
if (!$this->upload->do_upload('filename'))
{
// case - failure
$upload_error = array('error' => $this->upload->display_errors());
$this->load->view('addslideshows', $upload_error);
}
else
{
// case - success
$upload_data = $this->upload->data();
$filename = $upload_data['file_name'];
$image_id = $this->uri->segment(3);
$data['images'] = $this->Mpages->edit_slideshow($filename, $image_id);
$data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . $upload_data['file_name'] . '</strong> was successfully uploaded!</div>';
$this->load->view('editslideshows', $data);
}
}
models/Mpages.php
public function edit_slideshow($filename, $image_id)
{
$this->db->set('slideshow_image', $filename);
$this->db->where('image_id', $image_id);
return $this->db->update('slideshow');
}
Change your Model's function to this
public function edit_slideshow($filename, $image_id){
$this->db->where('image_id', $image_id);
$this->db->update('slideshow', $filename);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
rewrite your model
public function edit_slideshow($filename, $image_id)
{
$this->db->set('slideshow_image', $filename);
$this->db->where('image_id', $image_id);
$update=$this->db->update('slideshow');
if($update)
{
return true;
}
return false;
}

Grocery Crud default value after add

I need to add default images to post, if user do not select an image to upload.
Field to load the image optional.
How can i make it?
I use this controller.
public function news() {
$cur_user_id['user_id'] = $this->ion_auth->user()->row()->user_id;
$this->db->update('news', $cur_user_id);
$crud = new grocery_CRUD();
$crud->set_table('news')
->display_as('title', 'Заголовок')
->display_as('content', 'Текст')
->display_as('date', 'Дата')
->display_as('urlpict', 'Изображение')
->display_as('hide', 'Отображение')
->display_as('tags', 'Теги')
->display_as('add_new_tags', 'Добавить новые теги')
->display_as('menu_id', 'Раздел меню');
$crud->unset_columns('user_id');
$crud->required_fields('title', 'content', 'date', 'hide');
//relation
$crud->set_relation('menu_id', 'my_menu', 'name');
$crud->set_relation_n_n('tags', 'tag2art', 'tags', 'art_id', 'tag_id', 'tag');
//configuration for uploading
$this->config->set_item('grocery_crud_file_upload_allow_file_types', 'gif|jpeg|jpg|png');
$crud->set_field_upload('urlpict', 'assets/uploads/images');
//callback function
$crud->callback_after_upload(array($this, 'func_callback_after_upload'));
$state = $crud->getState();
$state_info = $crud->getStateInfo();
if ($state == 'add') {
$crud->fields('title', 'content', 'date', 'urlpict', 'hide', 'tags', 'add_new_tags', 'menu_id');
$crud->callback_add_field('add_new_tags', array($this, 'add_field_callback_1'));
} else {
$crud->unset_fields('add_new_tags', 'views', 'user_id');
}
$output = $crud->render();
$this->load->view('administrator/news', $output);
}
It's my callback_function
function func_callback_after_upload($uploader_response, $field_info, $files_to_upload)
{
$config['image_library'] = 'gd2';
$config['source_image'] = $field_info->upload_path . '/' . $uploader_response[0]->name;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 175;
$config['height'] = 175;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
return true;
}
Mine solution
Instead $crud->callback_after_update(array($this, 'default_img'));
I used $crud->callback_after_insert(array($this, 'default_img'));
And my controller
function default_img($post_array, $primary_key) {
if (!$this->input->post('urlpict')) {
$default_img = array(
"id" => $primary_key,
"urlpict" => "news_default.png"
);
$this->db->update('news', $default_img, array('id' => $primary_key));
return true;
}
}

Resources