[php] delete image from folder PHP

I have a folder where I keep my images, named img/. I have a table with all of my images:

<table border="3">
    <tr>
        <td>    
            <?php
            $files = glob("img/*");
            foreach ($files as $file) {
                echo "<div class='divimages'>"; 
                echo '<img src="'.$file.'"/>';
                echo "<input type='submit' value='Delete image'/><br>";
                echo "</div>";  
            }
            ?>
        </td>
    </tr>   
</table>

How can I delete the image associated to the button with the value:"Delete image".

This question is related to php

The answer is


You can delete files in PHP using the unlink() function.

unlink('path/to/file.jpg');

You can try this code. This is Simple PHP Image Deleting code from the server.

<form method="post">
<input type="text" name="photoname"> // You can type your image name here...
<input type="submit" name="submit" value="Delete">
</form>

<?php
if (isset($_POST['submit'])) 
{
$photoname = $_POST['photoname'];
if (!unlink($photoname))
  {
  echo ("Error deleting $photoname");
  }
else
  {
  echo ("Deleted $photoname");
  }
}
?>

<?php

    require 'database.php';

    $id = $_GET['id'];

    $image = "SELECT * FROM slider WHERE id = '$id'";
    $query = mysqli_query($connect, $image);
    $after = mysqli_fetch_assoc($query);

    if ($after['image'] != 'default.png') {
        unlink('../slider/'.$after['image']);
    }

    $delete = "DELETE FROM slider WHERE id = $id";
    $query = mysqli_query($connect, $delete);

    if ($query) {
        header('location: slider.php');
    }

?>

First Check that is image exists? if yes then simply Call unlink(your file path) function to remove you file otherwise show message to the user.

              if (file_exists($filePath)) 
               {
                 unlink($filePath);
                  echo "File Successfully Delete."; 
              }
              else
              {
               echo "File does not exists"; 
              }

For deleting use http://www.php.net/manual/en/function.unlink.php Hope you'll can to write logic?