in PHP by

How to 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">




            $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>";  






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

1 Answer

0 votes
There are a few routes. One, the most simple, would involve making that into a form; when it submits you react to POST data and delete the image using unlink

DISCLAIMER: This is not secure. An attacker could use this code to delete any file on your server. You must expand on this demonstration code to add some measure of security, otherwise you can expect bad things.

Each image's display markup would contain a form something like this:

echo '<form method="post">';

  echo '<input type="hidden" value="'.$file.'" name="delete_file" />';

  echo '<input type="submit" value="Delete image" />';

echo '</form>';

...and at at the top of that same PHP file:

if (array_key_exists('delete_file', $_POST)) {

  $filename = $_POST['delete_file'];

  if (file_exists($filename)) {


    echo 'File '.$filename.' has been deleted';

  } else {

    echo 'Could not delete '.$filename.', file does not exist';



// existing code continues below...

You can elaborate on this by using javascript: instead of submitting the form, you could send an AJAX request. The server-side code would look rather similar to this.

Documentation and Related Reading

unlink -

$_POST -

file_exists -

array_key_exists -

"Using PHP With HTML Forms" -

Related questions

0 votes
+1 vote
asked Jun 23, 2019 in PHP by SakshiSharma
0 votes
asked Jun 22, 2019 in PHP by SakshiSharma
0 votes
asked Jun 27, 2020 in PHP by DavidAnderson