R. Panha
R. Panha

Reputation: 15

How Delete File and Image after upload from Codeigniter?

This my code controllers "contract.php"

function delete($con_id){
        //$year=$this->session->userdata('year');
        $path = ('/assets/upload/employees/contracts/');
        $get_file = $path.$con_id.'.jpg';
        $this->db->where('con_id',$con_id);
        $this->db->delete('sch_emp_contract');
        if(file_exists($get_file)){
            unlink(base_url("/assets/upload/employees/contracts/'.$con_id."));
        }

        $m='';
        $p='';
        if(isset($_GET['m'])){
            $m=$_GET['m'];
        }
        if(isset($_GET['p'])){
            $p=$_GET['p'];
        }

        redirect("employee/contract?m=$m&p=$p");
    }

This code View contract_list.php - Button Delete

<td width="1%" class="remove_tag">';
     if($this->green->gAction("D")){
     $tr .='<a title="Delete Contract" id="clk_del" class="clk_del">
<img rel="'.$contract['con_id'].'" src="'.site_url('../assets/images/icons/delete.png').'" onclick="delete_contrac (event);" style="width:20px;height:20px;"></a>';}$tr .='</td>

Function

function delete_contract(event){
    var r = confirm("Are you sure to delete this record !");
    if( r == true){
    var contr_id= $(event.target).attr('rel');
    location.href="<?PHP echo site_url('employee/contract/delete');?>/"+contr_id+"?<?php echo "m=$m&p=$p" ?>";
    }
}

Success Delete from Database but Folder file and Image upload can't delete.

Upvotes: 0

Views: 2664

Answers (2)

Gopal Joshi
Gopal Joshi

Reputation: 2358

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."));

Upvotes: 1

Nabin Kunwar
Nabin Kunwar

Reputation: 1996

Check if your file_exists returns true or false. Then try something like this.

$path = BASEPATH.'/assets/upload/employees/contracts/';//get absolute path
        $get_file = $path.$con_id.'.jpg';
        $this->db->where('con_id',$con_id);
        $this->db->delete('sch_emp_contract');
        if(file_exists($get_file)){
            unlink($get_file);
        }

Upvotes: 1

Related Questions