user5913892
user5913892

Reputation: 123

Delete file a file on the server(not local) with CodeIgniter(3)

I have a view named home_view, where there are several lists, for example libri(books).The user can upload and delete the files.

This is a snippet of home_view.php

<?php  


echo "<table>";
echo "<tbody>";
echo "</br>";

 foreach ($libri as $row):
?>
      <tr>
        <td>
          <div>
            </br>
         <img src="<?php echo base_url('Immagini/book.png'); ?>" />
          <a class="pdf" data-fancybox-type="iframe" rel="group" href="<?php  echo base_url($row['Url_suffix']) ?>"><?php echo $row['Nome']; ?> </a>
        <a  class="deleteUser" href="javascript:void(0)" rel="<?php  echo site_url('libro/elimina/'.$row['ID']) ?>"><img src="<?php echo base_url('Immagini/button_close.png'); ?>"/></a> 


            </div>
    </td>
    </tr>
<?php
 endforeach;

       ?> 

libri is a table of Mysql db and have different columns, Url_suffix is a Varchar(255) column where there's the folder/filename.pdf. IN the second anchor I delete with success, the row from the DB, but not the file. I tried to do something like this

<a  class="deleteUser"  rel="<?php  unlink($row['Url_suffix']);  ?>"><img src="<?php echo base_url('Immagini/button_close.png'); ?>"/></a>

but without success. What I'm wrong?

Update:

controller libro.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Libro extends CI_Controller {

 public function __construct()
 {
   parent::__construct();
   $this->load->helper("file");
 }

 public function elimina($libri_id) {

  //$libri_ID = $this->libri->get_one($libri_id);
 $result=$this->libri->did_delete_row($libri_id);

                    redirect(site_url('admin/dashboard'), 'refresh');


 }


}

?>

Upvotes: 0

Views: 167

Answers (1)

Asfo
Asfo

Reputation: 413

You can't use "unlink" in that way, basically you need to process which you want to delete on your controller, with some help of a model, example:

public function delete_file($route, $file){
   unlink($route . "/" . $file);
}

In a model so you can use it anywhere, the $route parameter will be the path to your directory where the file is stored, for example:

htdocs/website/static/books/user/

And the $file parameter will be the name with extension that you want to delete, like:

myfirstbook.pdf

then you will have the full route to the file and it will be deleted, you only have to call that funcion from the models in your controller where the link was given by that anchor, like

<a href="http://localhost/website/delete-file/$user/$name">Delete file</a>

And your controller will have something like

public function delete_file($user, $file){
   $this->load->model('YourModel', 'yourmodel');
   $path = FCPATH . "static/books/user/".$user;
   $this->yourmodel->delete_file($path, $file);
}

And its done. Hope it helps.

Upvotes: 2

Related Questions