CancelImage Upload

How to delete or remove a file in PHP

While deleting a file in PHP only requires one simple function, you will want to contain it in a pack of if statements that indeed check for whether or not the file first of all exists, and if it does you will want to know if it has indeed been deleted.

To accomplish this task we will therefore not only need the PHP delete function unlink(), but also file_exists(), which as the name indicates finds out if a file does indeed exist in it's specified location.

Here then is our combination of if statements that will help us monitor whether or not the file has actually been deleted:

<?php

      $file = "path/file.txt";

      if(file_exists($file))
      {

            if(unlink($file))
            {

                  echo "The file <i>".$file."</i> has been deleted.";

            }
            else
            {

                  echo "The file <i>".$file."</i> could not be deleted.";

            }
      }
      else
      {

            echo "The file <i>".$file."</i> could not be found.";

      }

?>

As you see when a file has been specified in the wrong location we will be confronted with the error message:

"The file path/file.txt could not be found."

On the other hand if the file does exist but something went wrong you will be confronted with the following message:

"The file path/file.txt could not be deleted."

If the unlink has been successful as is the desired result you will see the following:

"The file path/file.txt has been deleted."


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com