Deleting a File


#1

I would like to learn the best (most proper / safest) way to delete a file from the server via PHP.

In my case, I am the only admin and the only one with the access to delete a file. The files are all image files.

I have read a couple different ways on how to do this, and some recommend opening the file and closing the file first. I just wanted to see what the experts here think is the best way to do this.

Currently, I’m looking at doing it this way:

    if (file_exists($file)) {
        unlink($file);
    } else {
        // Error display stuff
    }

Any concerns with this? Should I open and close the file first?


#2

I’m no expert but there’s also a chance unlink() will fail and return false and you should check for that as well.


#3

If you do not have the proper permissions on the file or if it is open in another process unlink will fail.