How to delete a file using PHP.

This is a short tutorial on how to delete a file using PHP. To do this, we will be using the PHP function unlink.

For those of you who are not in the know, the unlink function takes in one parameter: The $filename. This $filename parameter can contain a relative path or absolute path to the file.

Let’s take a look at the following snippet, in which we delete a file called file.txt:

If the file is successfully deleted, the unlink function will return a boolean TRUE value. However, if the file can not be deleted, then it will return a FALSE value. Furthermore, a warning error will be omitted by PHP.

For example, if the file does not exist, then the following warning will occur:

Warning: unlink([filename]): No such file or directory in /path/to/file on line [line number]

As a result, it is probably a good idea to check if the file exists before you attempt to delete it.

Using PHP to delete a file if it exists.

In most cases, you will want to make sure that a file actually exists before you attempt to delete it. Thankfully, this is pretty easy to do with the is_writable function:

In the example above, our code will only attempt to delete the file if is_writable returns a TRUE value. As a result, we can avoid any ugly E_WARNING messages.

unlink and permission issues.

The reason that I used is_writable instead of is_file is because is_writable will help protect against permission issues. This is because the function doesn’t just check to see if the file exists, it also checks to see if PHP has write access to the file. If PHP does not have write access to the file, then it will not be able to delete it.

If PHP does not have permission to delete the file in question, the following warning message will be omitted:

Warning: unlink([filename]) [function.unlink]: Permission denied

In cases like this, you will need to give PHP write access to the directory in question. However, that is far outside the scope of this article.

Delete a file if it is older than X days.

If you only want PHP to delete a file that is older than a day, etc, then you can do something like this:

In the PHP snippet above, we got the file’s last modification date. If 86400 seconds have passed since the file was last modified, we attempt to delete it. Obviously, you can change this time period to suit your own needs. For example, if you wanted to delete the file if it was older than an hour, then you would change the $deleteAfter variable to 3600.

And that’s it! Hopefully, you found this tutorial useful!

Related: Delete all files from a folder using PHP.

Facebook Comments