Search code examples
phpimagecodeigniterunlink

codeigniter. delete_files not working when trying to delete image from directory


I am trying to delete an image using a button.

when i click the button i use onClick"'.delete_files(assets/uploads/.$image->filename).'"

But nothing is happening. The image is still where it was before I clicked the button. When I do a print_r($image->filename) I get the 3 names of my images shown on the page.

this is my code:

<table class="images">
    <tr>
    <br/>
    <? foreach($images as $image) { ?>
    <td>
    <a href="assets/uploads/<?= $image->filename ?>" rel="lightbox" title="<?= $image->filename; ?>">
    <img src="<?php echo base_url();?>assets/uploads/<?= $image->filename; ?>" width="200px">
    </a>
<?= '<input type="button" value="Delete" onclick"'.delete_files('assets/uploads/'.$image->filename).'"><br/>'; ?>
    </td>
    <? } ?>
    </tr>
</table>

I wonder if the path is right. but the assets folder is in my root. httpdocs/assets/uploads and my codeigniter folder is at httpdocs/application/ so that should work.


Solution

  • I am pretty sure that you are calling php function on onclick attribute of the button which is wrong you cannot call directly server side functions on the html element's attribute

    While using codeigniter make a function in your controller and place the anchor tag instead of button like

    <table class="images">
    <tr>
    <br/>
    <? foreach($images as $image) { ?>
    <td>
    <a href="assets/uploads/<?= $image->filename ?>" rel="lightbox" title="<?= $image->filename; ?>">
    <img src="<?php echo base_url();?>assets/uploads/<?= $image->filename; ?>" width="200px">
    </a>
    
    <?= '<a  title="Delete" href="'.site_url().'controller/delete_files/'.$image->filename).'"><br/>'; ?>
    </td>
    <? } ?>
    </tr>
    </table>
    

    In your controller make a function delete_files()

     function delete_files($image_name){     
     // write the code to delete or unlink $image_name
     unlink('ROOT PATH'.$image_name);
     }