How to unlink (delete) an image in CodeIgniter
Asked Answered
S

12

11

I try to unlink an image in CodeIgniter, but the unlink function shows:

notice Undefined index: userfile

Here is my code

<?php
    function get_from_post(){
        $data['logo_name']  = $this->input->post('logo_name',TRUE);
        $data['logo_thumb'] = $_FILES['userfile']['name'];
        return $data;
    }

    function deleteconf($data){
        $data= $this->get_from_post();
        $update_id=$this->uri->segment(3);

        @unlink(base_url.'image/logo_thumb'.$logo_thumb);

        $query= $this->_delete($update_id);     
    }
?>
Skimpy answered 8/2, 2014 at 5:53 Comment(3)
Where does $logo_thumb come from? I can't see where you've assigned the value.Continuate
its come from post(form value)Skimpy
And what about base_url? Is that the CodeIgniter base_url()?Continuate
C
4

the unlink function shows notice Undefined index: userfile

The upload form, using multipart/form-data

Make sure you've use enctype="multipart/form-data" attribute/value for your upload form.

<form action="" method="post" accept-charset="utf-8" enctype="multipart/form-data">

From the MDN:

enctype
multipart/form-data: Use this value if you are using an <input> element with the type attribute set to "file".

If you're going to use CodeIgniter form helper, you could use form_open_multipart() function:

This function is absolutely identical to the form_open() tag above except that it adds a multipart attribute, which is necessary if you would like to use the form to upload files with.

Deleting files, File path vs URL address

PHP unlink() function accepts the Path of the file as the first argument. Not the URL Address.

The base_url() helper function returns the URL address of the site, which you've set in the config.php file.

You'll have to use the path of the file on your server, as follows:

unlink('/path/to/image/image_name.jpg'); // This is an absolute path to the file

You could use an Absolute or Relative path, but note that the relative path is relative to the index.php file. i.e. If the image/ folder is placed beside index.php file, you should use image/image_name.jpg as the file path:

unlink('image/image_name.jpg'); // This is a relative path to the file
Continuate answered 11/2, 2014 at 10:16 Comment(0)
A
2

If you want to upload a photo for user profile and also at the time the old user photo should be deleted by using unlink method in codeignitor

$query = $this->db->where('profile_id',$profile_id)->get('users')->row();
$result = $query->photo;
$result = http://localhost/abc/user_photo/FE12563.jpg

if ($result) {
        $dd = substr($result, strlen(base_url()));
        unlink($dd);
        return  $this->db->set('photo',$photo)->where('profile_id',$profile_id)->update('users');
}
Allegedly answered 22/11, 2017 at 12:46 Comment(0)
N
1

Suppose you have the file name in the database and your file is abc.jpg. Then to unlink that in Code Igniter just do -

$file = "abc.jpg";
$prev_file_path = "./assets/uploads/files/".$file;
if(file_exists($prev_file_path ))
    unlink($prev_file_path );

My file upload path is "public_html/assets/uploads/files/". I am writing the above code in my controller which is "public_html/application/controllers/MyController.php". So the path will be same which I used in my CI file upload section. i.e.

...
$config['upload_path']   = './assets/uploads/files';
...

So we used relative path in both the upload and unlink section. So if the upload works perfectly then this will also work perfectly.

Nitride answered 14/10, 2018 at 6:31 Comment(0)
O
0
function get_from_post(){
      $filename = $_POST['logo_name'];
      $path = $_SERVER['DOCUMENT_ROOT'].'/projectname/uploads/'.$filename ;
      if(is_file($path)){
        unlink($path);
        echo 'File '.$filename.' has been deleted';
      } else {
        echo 'Could not delete '.$filename.', file does not exist';
      }
  }
Osculation answered 8/2, 2014 at 6:7 Comment(1)
i try ed its shows notice Undefined index: file_exitsSkimpy
F
0

First check your file input name. Is it "userfile" or not? if not then add it and then run it once again.

Filberto answered 8/2, 2014 at 13:2 Comment(6)
input name is userfileSkimpy
print the $_FILES array and check whether it contains "userfile" or notFilberto
i try to print the $_FILES its shows again undefined index :userfileSkimpy
try this print_r($_FILES);Filberto
output produce an empty array: Array()Skimpy
that means there is no file uploaded by user. In such case you can check whether the $_FILES is empty or not and if its empty then assign a default thumbFilberto
O
0

base_url() function returns url of you project but here you have to use directory path of file which you want to delete.

$path = BASEPATH.'/assets/upload/employees/contracts/'; 
$get_file = $path.$con_id.'.jpg'; 
 if(file_exists($get_file)){ 
 unlink($get_file); 
 }

instead of unlink(base_url("/assets/upload/employees/contracts/'.$con_id."));

Outman answered 25/8, 2018 at 7:49 Comment(0)
A
0

First unlink function work only with path (without url), so please remove base_url() function.

Then in your first function $_FILES array doesn't contain userfile index, that's why getting error.

NOTE:- Before using unlink i would like to use also file_exists() function, first it will check if file is exist on same path then use unlink function (for error handling).

Like that -

<?php 
if(file_exists(filePath))
{
 unlink(filePath);
}

?>

Please fix both issue.

Thanks

Affettuoso answered 25/8, 2018 at 10:42 Comment(0)
D
0

You can do like this, you need to get first the path of directory from where you have uploaded your image. Exemple:

//this is your url
$mainPath='https://google.com/uploads/image/16.jpeg';
$uploadedDirectory=str_replace("https://google.com/","./", $mainPath);
//now you get path like this ./uploads/image/16.jpeg
if(unlink($uploadedDirectory)) {
    $this->db->where('prodId',$id);
    $this->db->delete('products');
}
Designate answered 1/6, 2022 at 17:55 Comment(0)
R
-1
$this->load->helper("file");

just add above line before unlink

unlink($path);
Roz answered 17/6, 2016 at 9:37 Comment(0)
J
-1

Can you please use this code to remove image on folder.

unlink(realpath('uploads/' . $_image));

"uploads" : Image exist in uploads folder. "$_image" : Image file name

PHP functions: 1 : unlink() 2 : realpath()

The above code successfully working on my site to delete image on folder.

Juno answered 13/12, 2017 at 9:47 Comment(0)
Y
-1
# CodeIgniter 3
# These methods will give you the document root path in CodeIgniter 3. You can use this path to construct URLs, file paths, or for any other purposes that require the document root.
    
         public function delete()
         {
            $id = $this->input->get('id');
    
    
            if(!empty($id))
            {
                $this->db->select("pdf_link");
                $this->db->from("ad_study");
                $this->db->where("st_id",$id);
    
                $query = $this->db->get();
                $data = $query->row_object();
    
                // $file = base_url('uploads/'.$data->pdf_link);
                $file = FCPATH.'/uploads/'.$data->pdf_link;
    
                if (file_exists($file)) {
                    if (unlink($file)) {
                        echo "File deleted successfully.";
                    } else {
                        echo "Unable to delete the file.";
                    }
                } else {
                    echo "File does not exist.";
                }
    
                // die;
                $this->db->where('st_id',$id);
                $this->db->delete("ad_study");
    
                $this->session->set_flashdata('db_success','Success - Data Delete Successfully ');
                redirect('admin/material');
            }
         }
Yesteryear answered 2/10, 2023 at 7:29 Comment(0)
C
-2

try this code

unlink(base_url().'/image/logo_thumb'.$logo_thumb);

Note: You didn't assign / declare $logo_thumb in your deleteconf().

Please check your code.

Cane answered 8/2, 2014 at 5:57 Comment(2)
i try ed its shows notice Undefined index: userfileSkimpy
I think you did not post full code. userfile variable doesn't exist in your code. Post full code clearly. Otherwise your question will be flagged as unclear.Cane

© 2022 - 2024 — McMap. All rights reserved.